简体   繁体   English

根据Python中的多个值在元组列表中查找一项

[英]Finding an item in list of tuples according to more than one value in Python

I have a list of tuples, and want to know if a specific item is in the list according to a subset of the tuple's values. 我有一个元组列表,并且想根据元组值的子集知道列表中是否有特定项目。 One can us a list comprehension, and check its length (like in the following example), but I want directly to check if the item exists or not. 我们可以列表理解,并检查其长度(如以下示例所示),但我想直接检查该项目是否存在。 In the following example, I have a list of tuples, each one has 3 items, and I'm trying to find if an item with the values '1' and '2' for the first two values exists in the list. 在下面的示例中,我有一个元组列表,每个元组都有3个项目,并且我试图查找列表中是否存在前两个值分别为'1'和'2'的项目。 I don't care about the third value. 我不在乎第三个值。

if len([1 for x, y, _ in tuple_list if x=='1' and y=='2']) > 0:
    do_something

Ok, I've found a nice solution for that, using operator.itemgetter: 好的,我已经找到了一个很好的解决方案,使用operator.itemgetter:

from operator import itemgetter
if ('1', '2') in map(itemgetter(0,1), tuple_list):
    do_something

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

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