簡體   English   中英

將一個元組附加到另​​一個元組python中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM