将元组列表转换为字符串Python [英] Converting lists of tuples to strings Python
问题描述
例如,我已经在python中编写了一个返回列表的函数
I've written a function in python that returns a list, for example
[(1,1),(2,2),(3,3)]
但是我希望输出为字符串,这样我就可以将逗号替换为另一个字符,从而使输出为
But i want the output as a string so i can replace the comma with another char so the output would be
'1@1' '2@2' '3@3'
有什么简单的方法吗?:) 感谢您提前提出的提示
Any easy way around this?:) Thanks for any tips in advance
推荐答案
这看起来像tuple
的list
,其中每个tuple
具有两个元素.
This looks like a list
of tuple
s, where each tuple
has two elements.
' '.join(['%d@%d' % (t[0],t[1]) for t in l])
当然可以简化为:
' '.join(['%d@%d' % t for t in l])
甚至:
' '.join(map(lambda t: '%d@%d' % t, l))
l
是您的原始list
.这会为列表中的每个元组生成"number @ number"对.然后将这些对与空格(' '
)连接起来.
Where l
is your original list
. This generates 'number@number' pairs for each tuple in the list. These pairs are then joined with spaces (' '
).
当我第一次开始使用Python唤醒时,join
语法对我来说有点奇怪,但是
The join
syntax looked a little weird to me when I first started woking with Python, but the documentation was a huge help.
这篇关于将元组列表转换为字符串Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!