[英]Iterating over two lists at the same time and try to find if a number in one list is bigger than items in the other list
[英]Checking if a number in a list is bigger than the last number in the same list
我需要檢查列表中的數字是否增加,我試過這樣做:
for x in lines:
if(lines[x] > lines[x-1]):
++times_increased
但它似乎不起作用並返回錯誤“列表索引必須是整數或切片,而不是 str”該列表稱為行,因為我從 txt 文件獲取輸入數據並且每一行都是我擁有的新數字與該文件中的最后一個數字進行比較。
for x in lines
的循環給出了可迭代lines
的每個元素,這些元素似乎是字符串。
考慮使用for x in range(len(lines))
來遍歷所有索引,或者更 Pythonic for n,m in zip(lines, lines[1:])
,其中 n 和 m 是行中的相鄰數字。
此外,在 python 中, ++times_increased
不會將 times_increased 加一。 而是做times_increased = times_increased + 1
或簡寫版本times_increased += 1
。
請注意,需要使用 int 函數將數字從字符串轉換為整數,即 int(lines[x]) 或 int(n)。
您可以使用 zip() 將每個元素與其后繼元素配對,並將比較結果提供給 sum() function(True 將計為 1,False 計為 0):
times_increased = sum(a<b for a,b in zip(lines,lines[1:]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.