I'm looking for a way to compare 2 elements in single list of python. 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.
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
:
>>> 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 ;-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.