简体   繁体   中英

Find element in list

I have a list like

list_a = [(1, 2), (2, 3), (4, 5)]

and now using this list i wanted to find a element which has last value 3 any short method to achieve this? it should return (2,3)

For example:

In [1]: list_a = [(1, 2), (2, 3), (4, 5)]

In [2]: next(x for x in list_a if x[1] == 3)
Out[2]: (2, 3)

Note that it returns a single element, not a list of them (seems to be what you are asking). If there are multiple tuples, the first one is returned.

for item in list_a:
    if item[-1] == 3:
        return item

Or, if you might want to return multiple values:

return_list = []
for item in list_a:
    if item[-1] == 3:
        return_list.append(item)
return return_list

something simple like

for x in list_a: 
    if x[1] == 3: print x

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