简体   繁体   English

如果带有元组的语句并从列表中删除元组

[英]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. 我想我可以遍历列表并手动检查,但我觉得有一种pythonic方式来解决这个问题。 Afterwards, I would like to remove all tuples that have a (1, ) in the first position. 之后,我想删除所有在第一个位置有(1,)的元组。 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: 要检查任何元组是否有1,2或3作为第一项,您可以使用带有生成器表达式的any函数,并删除所有元组作为第一项的1,您可以使用如下列表推导:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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