Reputation: 69
I have a list of a = [("apple", "red"), ("pear", "green"), ("orange", "orange"), ("banana", "yellow"), ("tomato", "red")]
I want to iterate through this list and if a[1] = "red"
, how do I append the whole tuple ("tomato", "red")
and ("apple", "red")
such that it will appear in b=[]
list as b = [("tomato", "red), ("apple", "red")]
?
Upvotes: 0
Views: 567
Reputation: 285
I second the list comprehension, you can even do it with the names of the things.
b = [(fruit, color) for fruit, color in a if color == "red"]
or if you wanna do it in a loop:
b = []
for fruit, color in a:
if color == "red":
b.append((fruit, color))
or if you wanna do multiple variations:
def fruitByColor(ogList, filterList):
return ([(fruit, color) for fruit, color in ogList
if color in filterList])
fruitByColor(a, ["green", "red"])
Upvotes: 1
Reputation: 697
Try this:
b = []
a = [("apple", "red"), ("pear", "green"), ("orange", "orange"), ("banana", "yellow"), ("tomato", "red")]
if a[1][1] == "red":
b.append(("tomato", "red"))
b.append(("apple", "red"))
print(b)
The a[1][1]
accesses the second element in the array a
and the second element of the tuple in that element
Upvotes: 0
Reputation: 95927
Just append the tuple:
In [19]: a = [("apple", "red"), ("pear", "green"), ("orange", "orange"), ("banana", "yellow"), ("tomato", "red"), ('avocado','green')]
In [20]: reds = []
In [21]: for pair in a:
...: if pair[1] == 'red':
...: reds.append(pair)
...:
In [22]: reds
Out[22]: [('apple', 'red'), ('tomato', 'red')]
However, it seems to me you might be looking for a grouping, which could conveniently be represented with a dictionary of lists:
In [23]: grouper = {}
In [24]: for pair in a:
...: grouper.setdefault(pair[1], []).append(pair)
...:
In [25]: grouper
Out[25]:
{'green': [('pear', 'green'), ('avocado', 'green')],
'orange': [('orange', 'orange')],
'red': [('apple', 'red'), ('tomato', 'red')],
'yellow': [('banana', 'yellow')]}
Upvotes: 1
Reputation: 857
You can create a dictionary of tuples with colors as keys and values as list of fruits as follows:
colors={}
for i in range(len(a)):
if a[i][1] not in colors:
colors[a[i][1]]=[a[i][0]]
else:
colors[a[i][1]].append(a[i][0])
Output:
{'green': ['pear'],
'orange': ['orange'],
'red': ['apple', 'tomato'],
'yellow': ['banana']}
Upvotes: 0
Reputation: 5437
Use a list comprehension
b = [tup for tup in a if tup[1] == "red"]
print(b)
[('apple', 'red'), ('tomato', 'red')]
Upvotes: 8