thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]
How do I say:
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}]
How do I say:
If "red" is in thelist and time does not equal 2 for that element (that's we just got from the list):
Using any() to find out if there is an element satisfying the conditions:
>>> any(item['color'] == 'red' and item['time'] != 2 for item in thelist)
False
any([...]) to get a classical list comprehension. (see python.org/dev/peps/pep-0289 for more on generator expressions)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}])
for i in thelist iterates through thelist, assigning the current element to i and doing the rest of the code in the block (for each value of i)
Thanks for the catch, Benson.
Well, there's nothing as elegant as "find" but you can use a list comprehension:
matches = [x for x in thelist if x["color"] == "red" and x["time"] != 2]
if len(matches):
m = matches[0]
# do something with m
However, I find the [0] and len() tedious. I often use a for loop with an array slice, such as:
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
You can do most of the list manipulation in a list comprehension. Here's one that makes a list of times for all elements where the color is red. Then you can ask if 2 exists in those times.
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()
You can condense that even further by eliminating the variable "reds" like this:
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()