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):
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.
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()
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
for val in thelist:
if val['color'] == 'red' and val['time'] != 2:
#do something here
But it doesn't look like that's the right data structure to use.
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