我想在 Python 的 for 回圈中檢查串列中的當前元素是否大于串列中的所有其他先前元素:
list_height = [187, 241, 319, 213, 541, 259, 319, 381] # an example, input depends on the user
length = len(list_height)
list_floor2 = [] # empty list for storage purposes
# For loop
for i in range(length):
floor1 = list_height[i]
if i == 0:
list_floor2.append(floor2)
elif list_height[i] > list_height[0] and list_height[i] > list_height[i - 1]:
floor1 = list_hoogte[i - 1]
list_floor2.append(floor2)
而不是list_height[i] > list_height[i - 1]在 elif 陳述句中,我不僅想檢查當前是否索引(i) > list_height 中的前一個元素(因此不僅是 index i - 1),而且當前是否索引list_height 中的(i) > 所有先前元素。
如何選擇串列中的所有先前元素?我試過了all(),list_height[:i]但我總是遇到同樣的錯誤:
TypeError: '>' not supported between instances of 'int' and 'list'
uj5u.com熱心網友回復:
你可以用enumerateand來做到這一點max,
[v for i, v in enumerate(list_height) if v >= max(list_height[:i 1])]
# Output
[187, 241, 319, 541]
uj5u.com熱心網友回復:
正如已經在評論中提到的那樣,您實際上不需要檢查每個元素直到當前索引。檢查每次迭代的最大值,如果當前數字較大,則您有當前最大值currrent_max,否則繼續。如果有一個新的最大值(它也自動大于之前的每個數字),則將該數字分配為current_max并將當前值附加到第二個串列中。
list_height = [187, 241, 319, 213, 541, 259, 319, 381]
list_floor2 = []
for i, num in enumerate(list_height):
if i==0:
list_floor2.append(num)
current_max = num
else:
if num >= current_max:
current_max = num
list_floor2.append(num)
print(list_floor2)
[187, 241, 319, 541]
uj5u.com熱心網友回復:
這是我的解決方案:
for 回圈將遍歷list_height串列。使用該all函式,將檢查當前值 ( value[1]) 是否大于串列中的任何先前數字。如果為 True,它將在末尾列印一個值True,否則將在False末尾列印一個值。
list_height = [187, 241, 319, 213, 541, 259, 319, 381]
for value in enumerate(list_height):
if all(x < value[1] for x in list_height[0:value[0]]):
print(f"{value[0]}-{value[1]} : True")
else:
print(f"{value[0]}-{value[1]} : False")
輸出:
0-187 : True
1-241 : True
2-319 : True
3-213 : False
4-541 : True
5-259 : False
6-319 : False
7-381 : False
或者,如果您想要更簡潔的代碼:
list_height = [187, 241, 319, 213, 541, 259, 319, 381]
for i,num in enumerate(list_height):
val = all(x < num for x in list_height[0:i])
print(f"{i}-{num} : {val}")
這提供了相同的輸出。
uj5u.com熱心網友回復:
length = len(list_height)
list_floor2 = [] # empty list for storage purposes
# check whether the current element in my list is larger than all the other previous elements in the list
def Check(i):
is_larger=True
for j in range(i):
if(list_height[j] > list_height[i]):
is_larger=False
break
return is_larger
# For loop
for i in range(length):
floor1 = list_height[i]
if Check(i):
list_floor2.append(floor1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512657.html
標籤:Python列表循环if 语句索引
上一篇:動態計算總計
