.join() 返回列表作为 python 中的结果

hab*_*ant 2 python string integer list

请有人解释一下为什么 .join() 的行为如下:

input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join(str(input))
print(a)
Run Code Online (Sandbox Code Playgroud)

结果是:

[ 1 ,   0 ,   5 ,   3 ,   4 ,   1 2 ,   1 9 ]
Run Code Online (Sandbox Code Playgroud)

不仅还有一个列表,而且还多了一个空间。怎么会?当我使用 map() 时它可以工作:

a = " ".join(list(map(str, input)))
Run Code Online (Sandbox Code Playgroud)

但我想知道我正在使用的 .join 方法有什么问题。

moz*_*way 6

str(input)返回一个 string '[1, 0, 5, 3, 4, 12, 19]',因此join使用该字符串的每个字符作为输入(字符串是可迭代的,就像列表一样),从而有效地在每个字符之间添加一个空格。

如果我们加入-'[-1-,- -0-,- -5-,- -3-,- -4-,- -1-2-,- -1-9-]'

相反,list(map(str, input))将每个数字转换为字符串,给出字符串列表 ( ['1', '0', '5', '3', '4', '12', '19']),join然后将其转换为'1 0 5 3 4 12 19'