简体   繁体   中英

Loop over List of tuples with one index of the tuple fixed

I'd like to loop over a list of tuples but having one of the indexes fixed with a determined value, like say we have this list:

myList = [(1,2,3) , (1,2,2), (2,3,4), (3,4,5), (1,3,4), (4,5,6), (4,6,8)]

and i wanted to loop over it fixing my first index with the value 1 , so in the loop I would be accessing those, and only those, values:

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

I know I can do this:

    newList = []
    for item in myList:
        if item[0] == 1:
            newList.append(item)

and then loop over this new list, but is there a direct or more perfomatic way of doing this?!

一种方法:

new_list = [item for item in myList if item[0] == 1]

You can also uso filter with a lambda. One benefit of this approach is that it returns a generator, so you do not need to instantiate the full filtered list (for example, if you only need the data to do subsequent processing).

>>> list(filter(lambda x: x[0] == 1, myList))
[(1, 2, 3), (1, 2, 2), (1, 3, 4)]

Use list comprehension to simplify your code:

tuples = [(1,2,3) , (1,2,2), (2,3,4), (3,4,5), (1,3,4), (4,5,6), (4,6,8)]

filtered_tuples = [t for t in tuples if t[0] == 1]

for t in filtered_tuples:
    # code here

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