我有一个元组列表:
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
答案 0 :(得分:2)
那是因为你选择的第一个元组不是每个元组的第一个值。
>>> s0 = '\n'.join(l[0] for l in MyList)
>>> s0
'abc\nghi\nmno'
答案 1 :(得分:0)
对于列表,您可以尝试以下内容:
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'
答案 2 :(得分:0)
l0 = []
l1 = []
for (v1, v2) in MyList:
l0.append(v1)
l1.append(v2)
s0 = '\n'.join(l0)
s1 = '\n'.join(l1)