简体   繁体   English

比较单个列表中的2个元素

[英]Compare 2 elements in single list

I'm looking for a way to compare 2 elements in single list of python. 我正在寻找一种方法来比较python单个列表中的2个元素。 For example if i have numbers = [1,3,5,7,9] i want to compare 1 with 3 and so on till the list ends. 例如,如果我的numbers = [1,3,5,7,9]我想将1与3进行比较,依此类推,直到列表结束。

Any suggestions? 有什么建议么?

for i,j in zip(numbers[:-1],numbers[1:]):
    compare(i,j)

This compares all adjacent elements, by lining up the list excluding the last element, and the list excluding the first element. 通过排列除最后一个元素之外的列表和不包括第一个元素的列表,将所有相邻元素进行比较。

Try using itertools : 尝试使用itertools

>>> from itertools import combinations
>>> for element in combinations(numbers, 2):
...     print element
...
(1,3)
(1,5)
(1,7)
(1,9)
(3,5)
(3,7)
(3,9)
(5,7)
(5,9)
(7,9)

For example: 例如:

def compare(x, y):
    """
    here you can put your code, using 'x' and 'y' var
    """
    if (x + y) % 2 == 0:
        return x

l = [1,3,5,7,9]
l2 = reduce(compare, l)
print l2

I hope help you ;-) 希望对您有所帮助;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM