简体   繁体   中英

Appending a tuple into another tuple python

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")] ?

Use a list comprehension

b = [tup for tup in a if tup[1] == "red"]
print(b)
[('apple', 'red'), ('tomato', 'red')]

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')]}

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']}

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

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"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM