简体   繁体   English

在 Python 中的列表列表中查找值是否存在

[英]Find if a value exists in a list of lists in Python

I have a list of lists like this:我有一个像这样的列表:

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I now want to find if a value exists in my_list , and I need to do this in the most efficient way.我现在想查找my_list是否存在一个值,我需要以最有效的方式执行此操作。 I will use it in the following way:我将通过以下方式使用它:

if my_value in my_list:
    # do something

I have tried 2 versions as below.我已经尝试了 2 个版本,如下所示。

# 1
if any(my_value in sublist for sublist in my_list)

# 2
for sublist in my_list:
    if my_value in sublist:
        return True

I find version 1 easier to read and doesn't require a separate function call.我发现版本 1 更易于阅读并且不需要单独的函数调用。 But does the any() function stop when it finds the value, or does it loop through the entire list?但是 any() 函数在找到值时会停止,还是会遍历整个列表? And is there a better, or more pythonic, way of doing this lookup?是否有更好或更 Pythonic 的方式来进行此查找?

The difference seems to be negligible with the second version only slightly faster.第二个版本的差异似乎可以忽略不计,只是稍微快一点。

my_list = [np.random.randint(1, 10000, 1000) for v in range(1000)]
my_value = np.random.randint(1, 10000, 1)[0]
def v1(my_list):
    if any(my_value in sublist for sublist in my_list):
        return True
    return False

def v2(my_list):
    for sublist in my_list:
        if my_value in sublist:
            return True
    return False

print(my_value)
%timeit v1(my_list)
%timeit v2(my_list)

>> 3012
>> 56.9 µs ± 3.1 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>> 51.2 µs ± 383 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

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

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