简体   繁体   中英

If statements with tuples and removing tuples from list

I am trying to check a list of tuples for certain types of tuples. I thought the _ operator would work here, but it doesn't work. I guess I could iterate through the list and check by hand, but I feel there is a pythonic way of solving this. Afterwards, I would like to remove all tuples that have a (1, ) in the first position. A filter would be my try for the removal process.

self.bids = [(1,1),(1,2),(1,3),(2,0),(3,1),(3,2)] 
if (1,_) in bids or (2,_) in bids or (3,_) in bids:
                possibleModes.remove((1,_))
                return possibleModes

_ is just a regular variable name, not a wild card or operator, although it's by convention used to hold values of no use.

To check if any of the tuples has 1, 2 or 3 as the first item, you can use the any function with a generator expression, and to remove all tuples with 1 as the first item, you can use a list comprehension like this:

if any(a in (1, 2, 3) for a, _ in self.bids):
    return [(a, b) for a, b in self.bids if a != 1]

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