[英]Appending a tuple into another tuple python
我有一个a = [("apple", "red"), ("pear", "green"), ("orange", "orange"), ("banana", "yellow"), ("tomato", "red")]
我想遍历此列表,如果a[1] = "red"
,我该如何附加整个元组("tomato", "red")
和("apple", "red")
,使其出现在b=[]
列表,如b = [("tomato", "red), ("apple", "red")]
?
使用列表理解
b = [tup for tup in a if tup[1] == "red"]
print(b)
[('apple', 'red'), ('tomato', 'red')]
只需追加元组:
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')]}
您可以创建一个元组字典,其中颜色作为键,值作为水果列表,如下所示:
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']}
尝试这个:
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
的第二个元素和该元素中元组的第二个元素
我仅次于列表理解,您甚至可以使用事物名称来实现。
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"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.