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

时间:2010-01-13 00:19:26

标签: python 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):

6 个答案:

答案 0 :(得分:13)

使用any()查明是否存在满足条件的元素:

>>> any(item['color'] == 'red' and item['time'] != 2  for item in thelist)
False

答案 1 :(得分:1)

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的每个值)

感谢Benson。

答案 2 :(得分:0)

您可以在列表推导中执行大部分列表操作。这是一个为颜色为红色的所有元素列出时间的列表。然后你可以询问那些时候是否存在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()

答案 3 :(得分:0)

嗯,没有什么比“查找”更优雅,但你可以使用列表理解:

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

for val in thelist:
    if val['color'] == 'red' and val['time'] != 2:
        #do something here

但它看起来不像是正确的数据结构。