[英]How to compare two adjacent items in the same list - Python
我正在尋找一種比較列表中兩個相鄰項目的方法,例如。 比較哪個值更高,然后我會相應地對它們進行排序。 這是一個用戶輸入的列表,所以不是if l[1] > l[2]
,因為我不知道列表的長度,所以我需要一個通用的聲明用於一個for循環。
我有想法for i in l: if x > i[index of x + 1]
中有類似於for i in l: if x > i[index of x + 1]
東西for i in l: if x > i[index of x + 1]
但不知道如何找到變量的索引。 感謝任何幫助,謝謝
編輯:我知道內置的排序功能,但只是想通過創建自己的:)來練習編碼和算法編寫
你可以使用zip()
:
In [23]: lis = [1,7,8,4,5,3]
In [24]: for x, y in zip(lis, lis[1:]):
....: print x, y # prints the adjacent elements
# do something here
....:
1 7
7 8
8 4
4 5
5 3
快速而丑陋的解決方案就是這樣(不要使用它!):
for i, item in enumerate(lst):
# here you can use lst[i + 1] as long as i + 1 < len(lst)
但是, 不要自己實現列表排序! 如果要創建新列表,請使用.sort()
進行就地sorted()
或sorted()
。 有關如何在python網站上對事物進行排序的非常好的指南 。
如果這不是你的意圖..而不是我上面發布的循環,還有一個更好的方法來迭代來自另一個SO問題列表中的塊:
import itertools
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.izip_longest(fillvalue=fillvalue, *args)
你喜歡這樣:
for x, y in grouper(2, lst):
# do whatever. in case of an odd element count y is None in the last iteration
你也可以使用內置的reduce函數
例如:
l = [1,2,3,4,5,6,7]
def my_function(a,b):
# your comparison between a and b
# return or print values or what ever you want to do based on the comparison
reduce(my_function, l)
減少將自動照顧i和i + 1。
希望能幫助到你。 :)
內置函數cmp ,可用於比較
我需要檢查列表中的所有項是否相同,所以我這樣做了:
def compare(x, y):
if x == y:
return x
return False
reduce(compare, my_list)
當你用[1,1,1,1,1,1]運行它時,它打印1,當其中一個數字不匹配時,它返回False .. simple
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.