简体   繁体   English

元组列表中元组之间的差异

[英]Difference between tuples in list of tuples

In Python, I have a list of tuples, that is: 在Python中,我有一个元组列表,即:

list_tup = [('123', 'A'), ('123', 'B')]

If I want to find out if there is, for example, the tuple ('123', 'A') , I just write: 如果我想找出是否存在例如元组('123', 'A') ,我只写:

('123', 'A') in list_tup
=> True

But what if I'd like to know if there's anything different from ('123', 'B') in that list of tuples, where the only different element is the second one ('B') ? 但是,如果我想知道该元组列表中的('123', 'B')是否有什么不同,其中唯一不同的元素是第二个('B')呢? Is it possible? 可能吗?

For example, I want to know if in list_tup there is something different from ('123', 'B'). 例如,我想知道list_tup中是否与('123','B')不同。

You can do something like: 您可以执行以下操作:

any(tup for tup in list_tup if tup[0] == '123' and tup[1] != 'B')

Basically filters the list of tuples to those that have '123' as the first value and not 'B' as the second value, and returns True if there are any (haha). 基本上将元组列表过滤为以'123'作为第一个值而不是'B'作为第二个值的元组,如果有(哈哈),则返回True。

But you can also modify this to get the list of all tuples that match the criteria by switching any to list . 但是,您也可以通过将any切换到list来修改它,以获取符合条件的所有元组的list

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

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