我正在嘗試使用下面的代碼來檢查是否允許某人乘坐過山車。第一部分用于創建二維串列,第二部分用于檢查。
heights = [165, 154, 156, 143, 168, 170, 163, 153, 167]
ages = [18, 16, 11, 34, 25, 9, 32, 45, 23]
heights_and_ages = list(zip(heights, ages))
heights_and_ages = [list(info) for info in heights_and_ages]
can_ride_coaster = []
for info in heights_and_ages:
for height, age in info:
if height > 161 and age > 12:
can_ride_coaster.append(info)
我在線上收到錯誤
if height > 161 and age > 18:
我認為是因為我使用了兩個變數 bcs 使用一個就可以了,但是在網上搜索后似乎沒有問題。我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
這里似乎不需要嵌套回圈。的每個元素heights_and_ages都是一對,您想遍歷它,將每一對解包到height和 中age。
for height, age in heights_and_ages:
if height > 161 and age > 12:
can_ride_coaster.append((height,age))
這有助于串列理解:
can_ride_coaster = [(h,a) for (h,a) in heights_and_ages if h > 161 and a > 12]
為什么你的代碼出錯?
假設info是[165, 18]。當你寫
for height, age in info:
您說的是“回圈遍歷info并將每個元素解壓縮到height, age”。
在該回圈的第一次迭代中,元素為 165,您嘗試將單個 int 值解包為多個變數。這就是為什么你得到int object is not iterable.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/400093.html
