简体   繁体   English

如何使用单行将列表/元组转换为 python 中的空格分隔字符串?

[英]How to turn a list/tuple into a space separated string in python using a single line?

I tried doing:我试着做:

str = ""
"".join(map(str, items))

but it says str object is not callable.但它说 str object 不可调用。 Is this doable using a single line?使用单行是否可行?

Use string join() method.使用字符串join()方法。

List:列表:

>>> l = ["a", "b", "c"]
>>> " ".join(l)
'a b c'
>>> 

Tuple:元组:

>>> t = ("a", "b", "c")
>>> " ".join(t)
'a b c'
>>> 

Non-string objects:非字符串对象:

>>> l = [1,2,3]
>>> " ".join([str(i) for i in l])
'1 2 3'
>>> " ".join(map(str, l))
'1 2 3'
>>> 

The problem is map need function as first argument.问题是map需要 function 作为第一个参数。

Your code你的代码

str = ""
"".join(map(str, items))

Make str function as str variable which has empty string.str function 设为str变量,该变量具有空字符串。

Use other variable name.使用其他变量名。

Your map() call isn't working because you overwrote the internal str() function.您的map()调用不起作用,因为您覆盖了内部str() function。 If you hadn't done that, this works:如果你没有这样做,这有效:

In [25]: items = ["foo", "bar", "baz", "quux", "stuff"]

In [26]: "".join(map(str, items))
Out[26]: 'foobarbazquuxstuff'

Or, you could simply do:或者,您可以简单地执行以下操作:

In [27]: "".join(items)
Out[27]: 'foobarbazquuxstuff'

assuming items contains strings.假设items包含字符串。 If it contains int s, float s, etc., you'll need map() .如果它包含int s、 float s 等,您将需要map()

Try:尝试:

>>> items=[1, 'a', 2.3, (1, 2)]
>>> ' '.join(str(i) for i in items)
'1 a 2.3 (1, 2)'

Alternatively, you can use repr function when mapping, which is similar to str (but more specialized behavior:或者,您可以在映射时使用repr function ,这类似于str (但更专业的行为:

A good resource: What is the difference between str and repr ?一个很好的资源: strrepr有什么区别?

items=[1, 'a', 2.3, (1, 2)]
' '.join(map(repr, items))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM