簡體   English   中英

在 Python 中連接元組列表中的元素

[英]Joining Elements from a List of Tuples in Python

我有一個元組列表:

MyList = [('abc', 'def'), ('ghi', 'jkl'), ('mno', 'pqr')]

我想做這樣的事情:

s0 = '\n'.join(MyList[0]) # get all tuple elements at index 0
s1 = '\n'.join(MyList[1]) # get all tuple elements at index 1

那是因為您選擇的是第一個元組而不是每個元組的第一個值。

>>> s0 = '\n'.join(l[0] for l in MyList)
>>> s0
'abc\nghi\nmno'

對於列表,您可以嘗試以下操作:

MyList = [('abc', 'def'), ('ghi', 'jkl'), ('mno', 'pqr')]

# Need to iterate over the list elements and pick the targeted tuple elem.
s0 = '\n'.join(item[0] for item in MyList) # 'abc\nghi\nmno'
s1 = '\n'.join(item[1] for item in MyList) # 'def\njkl\npqr'
l0 = []
l1 = []
for (v1, v2) in MyList:
    l0.append(v1)
    l1.append(v2)
s0 = '\n'.join(l0)
s1 = '\n'.join(l1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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