在元组列表中将元素连接在一起

时间:2017-12-25 10:11:10

标签: python dictionary

输入:

z = ", "
y = " "
chands = {'theboard': [('Diamonds', 'Four'), ('Clubs', 'Three'), ('Clubs', 'King'), ('Clubs', 'Two'), ('Hearts', 'Jack')]}

我的预期输出:

'Diamonds Four, Clubs Three, Clubs King, Clubs Two, Hearts Jack'

我试过了:

print chands["theboard"][0][0]+y+chands["theboard"][0][1]+z+chands["theboard"][1][0]+y+chands["theboard"][1][1]+z+chands["theboard"][2][0]+y+chands["theboard"][2][1] 

有没有更好的方法来打印它?

1 个答案:

答案 0 :(得分:1)

IIUC,map使用str.join + yz再次使用>>> z.join(map(y.join, chands['theboard'])) 'Diamonds Four, Clubs Three, Clubs King, Clubs Two, Hearts Jack' -

chands

如果您只想加入前3个元组,可以索引>>> z.join(map(y.join, chands['theboard'][:3])) 'Diamonds Four, Clubs Three, Clubs King' 并对结果进行切片 -

>>> z.join([y.join(x) for x in chands['theboard'][:3]])
'Diamonds Four, Clubs Three, Clubs King'

使用列表解析执行此操作的另一种方法是 -

Main