将元素合并到元组列表中

扎尔迪马尔

输入:

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] 

有更好的打印方法吗?

cs95

IIUC,使用map+ str.join,一次y又一次z-

>>> z.join(map(y.join, chands['theboard']))
'Diamonds Four, Clubs Three, Clubs King, Clubs Two, Hearts Jack'

如果您只想加入前三个元组,则可以chands对结果进行索引和切片-

>>> 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'

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章