简体   繁体   English

检查是一个元组,值在python列表中

[英]Check is a tuple with a value is in a list in python

Say I have a list of tuples in python (name, age). 假设我有一个python中的元组列表(名称,年龄)。

I want to check if there is a tuple in that list with "Mary" as the name, I don't care what the age is. 我想检查列表中是否有以“ Mary”为名称的元组,我不在乎年龄是多少。

How do I do this efficiently? 我如何有效地做到这一点?

any(a == 'Mary' for a, b in tuples) # check if any tuple has a name equal to Mary

If you are going to be doing many lookups make a set of the names: 如果要进行许多查找,请设置一组名称:

st = {name for name,_ in lst}

Then just check if name in st :... 然后只要检查if name in st :...

Set lookups are 0(1) using any for loop is going to be linear, if you always keep a set of names updating if a new tuple gets added then it will be a lot more efficient. 使用任何for循环的集合查找为0(1)将是线性的,如果您始终保持一组名称更新(如果添加了一个新的元组),则效率将大大提高。

If you actually plan on using the tuple with the name in it then you will have to iterate over the list of tuples and check each name. 如果您实际计划使用带有名称的元组,那么您将不得不遍历元组列表并检查每个名称。

If you must have a list then you're going to be stuck with O(n) (assuming the list is unsorted): 如果必须有一个列表,那么您将陷入O(n)(假设列表未排序)的情况:

my_tuple = ("Mary", 30)
my_list = [("Amber", 15), ("Mary", 25)]

def find_tuple(tuple_, list_):
    for val in list_:
        if val[0] == tuple_[0]:
            return val
    return None

Otherwise, if your data-structure is flexible, use a dictionary: 否则,如果您的数据结构灵活,请使用字典:

my_tuple = ("Mary", 30)
my_dict = {"Amber": ("Amber", 15), "Mary": ("Mary", 25)}

def find_tuple(tuple_, dict_):
    return dict_.get(tuple_[0], None)

Another possibility is to make a list of just the names and use the in operator: 另一种可能性是仅列出名称并使用in运算符:

names = [name for name, _ in tuples]
answer = "mary" in names

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

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