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):
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
這很好!我是否正確理解any()的括號是作爲生成器加倍的,因此any()會逐項評估列表理解,一旦找到滿足條件的項目,將返回True。 – Ben 2010-01-13 00:37:17
這是一個「生成器表達式」,可用於合理的Python版本(自2.4開始)。也可以寫'任何([...])'來獲得經典的列表理解。 (有關生成器表達式的更多信息,請參閱http://www.python.org/dev/peps/pep-0289/) – sth 2010-01-13 00:42:13
這就是那種讓我愛Python的東西。 – orokusaki 2010-01-13 00:49:10
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}])
因爲我在通過的thelist的thelist迭代,分配當前元素我和塊做代碼的其餘部分(每個i的值)
非常感謝Benson。
你可以在列表理解中完成大部分列表操作。這是一個爲所有顏色爲紅色的元素列出時間的列表。那麼你可以問在這些時候是否存在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()
您可以通過消除變量「紅魔」像這樣進一步凝聚的是:
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
我假設一個「最多一個」類型的發現。如果你想要所有的比賽,我會推遲到別人的回答。 – jpsimons 2010-01-13 00:27:15
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
也許這太挑剔了,但我建議你避免命名事物「list」,因爲你可能在某些時候需要訪問列表構造函數,並且覆蓋它會是一件恥辱。 – Benson 2010-01-13 21:20:55
Python使用「和」而不是「&&」 – Ponkadoodle 2010-03-25 22:26:56
for val in thelist:
if val['color'] == 'red' and val['time'] != 2:
#do something here
但它看起來並不像那使用正確的數據結構。
是否有「wallacoloo」的回答和列表理解/ Python的答案之間的速度差異? – TIMEX 2010-01-13 00:28:43