如何在 Python 中使用集合来查找列表成员资格?

编程入门 行业动态 更新时间:2024-10-07 16:26:31
本文介绍了如何在 Python 中使用集合来查找列表成员资格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定:

A = [['Yes', 'lala', 'No'], ['Yes', 'lala', 'Idontknow'], ['No', 'lala', 'Yes'], ['No', 'lala', 'Idontknow']]

我想知道 ['Yes', X, 'No'] 是否存在于 A 中,其中 X 是我不关心的任何东西.

I want to know if ['Yes', X, 'No'] exist within A, where X is anything I don't care.

我尝试过:

valid = False for n in A: if n[0] == 'Yes' and n[2] == 'No': valid = True

我知道 set() 在这种情况下很有用.但是怎么做呢?这可能吗?还是坚持使用原始代码对我来说更好?

I know set() is useful in this type of situations. But how can this be done? Is this possible? Or is it better for me to stick with my original code?

推荐答案

如果你想检查是否存在,你可以在 A 中['Yes', 'No']:

if you want check for existance you can just ['Yes', 'No'] in A:

In [1]: A = [['Yes', 'No'], ['Yes', 'Idontknow'], ['No', 'Yes'], ['No', 'Idontknow']] In [2]: ['Yes', 'No'] in A Out[2]: True

对于下一个案例尝试:

In [3]: A = [['Yes', 'lala', 'No'], ['Yes', 'lala', 'Idontknow'], ['No', 'lala', 'Yes'], ['No', 'lala', 'Idontknow']] In [4]: any(i[0]=='Yes' and i[2] == 'No' for i in A) Out[4]: True

或者你可以定义一个小函数:

or you can possibly define a little func:

In [5]: def want_to_know(l,item): ...: for i in l: ...: if i[0] == item[0] and i[2] == item[2]: ...: return True ...: return False In [6]: want_to_know(A,['Yes', 'xxx', 'No']) Out[6]: True

any(i[0]=='Yes' and i[2] == 'No' for i in A*10000) 实际上似乎比转换快 10 倍自己.

any(i[0]=='Yes' and i[2] == 'No' for i in A*10000) actually seems to be the 10 times faster than than the conversion itself.

In [8]: %timeit any({(x[0],x[-1]) == ('Yes','No') for x in A*10000}) 100 loops, best of 3: 14 ms per loop In [9]: % timeit {tuple([x[0],x[-1]]) for x in A*10000} 10 loops, best of 3: 33.4 ms per loop In [10]: %timeit any(i[0]=='Yes' and i[2] == 'No' for i in A*10000) 1000 loops, best of 3: 334 us per loop

更多推荐

如何在 Python 中使用集合来查找列表成员资格?

本文发布于:2023-11-30 15:34:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650523.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成员   资格   如何在   列表   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!