简体   繁体   中英

Comparing the elements within tuples

So I have got a list = [(0, [2, 0, 4], 1), (3, [2, 0, 4], 2), (1, [3, 0, 4], 2), (2, [3, 0, 4], 2)] where its elements are tuples that include an ID as its first element, a list within that always includes three random integers and then a time. Assume that this list will not be empty. I am struggling to write code that compares each individual component of the tuple elements and appending to a new list depending on a set of criteria. First criteria is the lists in the middle of each tuple element. I want to compare each tuple whose middle lists are the same, so in my list above comparing list[0] to list[1] and list[2] to list[3]. If there is a tuple with no duplicate list in the middle as any other tuples then append that tuple to a new empty list. Then for the elements with the matching lists within the tuples I want to compare the time values of those tuples, if it is the lowest time value for the tuples with the matching middle lists then that tuple will be appended to the new empty list. However, if this value is the same for the tuples with the matching middle lists I then want to compare their IDs and pick the lowest ID value. For the example list above the desired output would be [(0, [2, 0, 4], 1), (1, [3, 0, 4], 2)] because for the tuples with the matching list [2, 0, 4] the lowest value for time was 1 while for the tuples with matching list [3, 0, 4] and a matching value for time the lowest ID value was 1. Any help available? If there is anything needed to be clarified I will try my best to answer.

It would be easier if you gave us some more information, but a good way to start is something along the lines of

my_list = [1,2,3,8,0,2]
specific_value=0

for index, value in enumerate(my_list):
    if (value==specific_value) & (0 < index <len(my_list)-1):
        print(my_list[index-1:index+2])
    

There are probably better solutions, but this should point you in the right direction. The boundary check makes sure to avoid problems with the first and last element

I think this code snippet can help you. You may also need to check the availability of the elements idx-1, idx, and idx+1 to avoid IndexOutOfRangeException.

def f(l, search_term):
    idx = l.index(search_term)
    return [l[idx-1], l[idx], l[idx+1]]

example = [1,2,3,8,0,2]
new_list = f(example, 0)

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