繁体   English   中英

如何确定元素是否在列表中?

[英]How do I determine if an element is in a list?

thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]

我怎么说:

If "red" is in thelist and time does not equal 2 for that element (that's we just got from the list):

使用any()来确定是否存在满足条件的元素:

>>> any(item['color'] == 'red' and item['time'] != 2  for item in thelist)
False
def colorRedAndTimeNotEqualTo2(thelist):
    for i in thelist:
        if i["color"] == "red" and i["time"] != 2:
            return True
    return False

print colorRedAndTimeNotEqualTo2([{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}])

因为列表中的i会遍历该列表,将当前元素分配给i并执行块中的其余代码(对于i的每个值)

谢谢,本森。

您可以在列表理解中执行大多数列表操作。 这是列出所有颜色为红色的元素的时间的列表。 然后,您可以询问当时是否存在2。

thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
reds = ( x['time'] == 2 for x in thelist if x['color'] == red )
if False in reds:
  do_stuff()

您可以通过消除这样的变量“ reds”来进一步浓缩:

thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
if False in ( x['time'] == 2 for x in thelist if x['color'] == red ):
  do_stuff()

好吧,没有什么比“查找”更优雅,但是您可以使用列表理解:

matches = [x for x in thelist if x["color"] == "red" and x["time"] != 2]
if len(matches):
    m = matches[0]
    # do something with m

但是,我发现[0]和len()乏味。 我经常对数组切片使用for循环,例如:

matches = [x for x in thelist if x["color"] == "red" and x["time"] != 2]
for m in matches[:1]:
    # do something with m
list = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
for i in list:
  if i['color'] == 'red' && i['time'] != 2:
    print i
for val in thelist:
    if val['color'] == 'red' and val['time'] != 2:
        #do something here

但这似乎并不是使用的正确数据结构。

暂无
暂无

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

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