2013-08-26 17 views
0

遍歷列表元素的列表,並返回錯誤消息我有這樣一個列表的列表:如果整數具有一定值

麪包= [[「NAME1」,45,140] [「NAME2」,85, 95]]

大列表中每個列表中的第三個(或不包含[2])元素是用戶給出的變量計算的結果,不能高於80.如果它高於80我需要返回錯誤消息而不是打印計算結果。

我試過到目前爲止:

i = 0 
while i <= len(breadsticks): 
    if breadsticks[i][2] > 80: 
     print("you have entered too many breadcrums") 
    elif i == len(breadsticks): 
     for bread in breadsticks: 
       print(breadsticks[bread][2]) 
    i += 1 

我試圖做到這一點,不僅是不行的,這也是笨拙。有沒有其他的,順利的方式來給錯誤信息阻止這樣的事情?

+1

你幾乎從來沒有想用'循環I = 0;而我<=垃圾郵件:雞蛋......我+ = 1'。只要做'範圍(垃圾郵件)我:雞蛋...'。然而,即使這樣做也很少有用,因爲你可以用麪包棒做'麪包棒',甚至不用擔心指數。 – abarnert

回答

1

使用any() function用生成器表達式測試每個嵌套列表:

if any(bread[2] > 80 for bread in breadsticks): 
    print("You have entered too many breadcrumbs") 

需要找到任何針對測試是True這隻會測試儘可能多的嵌套列表。

請注意,這是簡單的,只是循環直接超過breadsticks在循環:

for bread in breadsticks: 
    print(bread[2]) 
+0

謝謝。完美的答案,正是我所期待的。 – Flowdorio

相關問題