Jol*_*onB 1 python arrays python-3.x
我从这个问题中学到了可以", ".join(var)在Python 中使用数组连接值.此代码适用于字符串,例如:
var = ["hello","world"]
print (", ".join(var))
Run Code Online (Sandbox Code Playgroud)
给出hello, world我想要的输出.
但是,当我在数组中使用数字时:
var = [1,2,3]
print (", ".join(var))
Run Code Online (Sandbox Code Playgroud)
它给出了一条错误消息:
Traceback (most recent call last):
File "C:\path\test.py", line 2, in <module>
print (", ".join(var))
TypeError: sequence item 0: expected str instance, int found
Run Code Online (Sandbox Code Playgroud)
然而,我希望输出为:
1, 2, 3
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以这样,它将打印所有数字,还有能力增加,所以我可以有任何数量的数字?
只需将数字转换为字符串即可join:
var = [1, 2, 3]
print(", ".join(map(str, var)))
Run Code Online (Sandbox Code Playgroud)
或使用列表理解:
print(", ".join([str(x) for x in var]))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |