简体   繁体   中英

Two pairs of consecutive values list python

If you have a list in python like this: list1 = [(1,2), (3,1), (4,1), (1,2), (3,1)]
If you have list1 in python and you want to find if two pairs of consecutive values in a list in python are equal like (1,2) and (3,1) is repeated twice and you want to update a variable lets say i to 2 based on this. How would you do this in python?

Here is how I got it, looped through the original list and made mini lists of every each pair, then I checked to see if that pair occurs twice.

lst = [(1,2), (3,1), (4,1), (1,2), (3,1)]

#iterate through list and append each pair of values
tmp = []
for i in range(0, len(lst)-1):
    tmp.append(lst[i] + lst[i+1])

#see if any of the pairs appear twice, if so add to new list and get the length of that list to be your count
output =  [x for x in tmp if tmp.count(x) > 1]
i = len(output)
print(i)

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.

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