我有一个元组列表:
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
'abcnghinmno'
对于列表,您可以尝试这样做:
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) # 'abcnghinmno'
s1 = 'n'.join(item[1] for item in MyList) # 'defnjklnpqr'
l0 = []
l1 = []
for (v1, v2) in MyList:
l0.append(v1)
l1.append(v2)
s0 = 'n'.join(l0)
s1 = 'n'.join(l1)