将元组添加到另一个元组python中

时间:2017-07-12 06:28:16

标签: python

我有a = [("apple", "red"), ("pear", "green"), ("orange", "orange"), ("banana", "yellow"), ("tomato", "red")]

的列表

我想遍历此列表,如果a[1] = "red",我如何追加整个元组("tomato", "red")("apple", "red"),使其在b=[]列表中显示为{ {1}}?

5 个答案:

答案 0 :(得分:8)

使用list comprehension

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

答案 1 :(得分:1)

只需附加元组:

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

但是,在我看来,您可能正在寻找一个分组,可以方便地用列表字典表示:

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

答案 2 :(得分:0)

您可以创建一个元组字典,其中颜色为键,值为水果列表,如下所示:

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

输出:

{'green': ['pear'],
'orange': ['orange'],
'red': ['apple', 'tomato'],
'yellow': ['banana']}

答案 3 :(得分:0)

试试这个:

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)

a[1][1]访问数组a中的第二个元素以及该元素中元组的第二个元素

答案 4 :(得分:0)

我是列表理解的第二名,你甚至可以用事物的名字来做。

b = [(fruit, color) for fruit, color in a if color == "red"]

或者如果你想在循环中这样做:

b = []
for fruit, color in a:
   if color == "red":
       b.append((fruit, color))

或者如果你想做多种变化:

def fruitByColor(ogList, filterList):
    return ([(fruit, color) for fruit, color in ogList 
             if color in filterList])

fruitByColor(a, ["green", "red"])