python - 在单行python3中打印一个int列表

标签 python python-3.x

我是 python 新手,我正在尝试在一行中扫描多个用空格分隔的数字(假设 '1 2 3' 作为示例)并将其添加到 int 列表中。我通过使用:

#gets the string 
string = input('Input numbers: ') 
#converts the string into an array of int, excluding the whitespaces
array = [int(s) for s in string.split()] 

显然它有效,因为当我输入 '1 2 3' 并执行 print(array) 时,输出是:

[1, 2, 3]

但我想在一行中打印,不带括号,数字之间有空格,如下所示:

1 2 3

我已经尝试过:

for i in array:
    print(array[i], end=" ")

但我得到一个错误:

2 3 Traceback (most recent call last):

print(array[i], end=" ")

IndexError: list index out of range

如何在一行中打印整数列表(假设我的前两行代码是正确的),并且没有括号和逗号?

最佳答案

是的,这在 Python 3 中是可能的,只需在变量之前使用 *,例如:

print(*list)

这将打印由空格分隔的列表。

(其中 * 是将列表转换为位置参数的 unpacking 运算符,print(*[1,2,3])print(1,2,3) 相同,另见 What does the star operator mean, in a function call? )

关于python - 在单行python3中打印一个int列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37625208/

相关文章:

python - 为什么 skimage 均值过滤器不适用于 float 组?

python - 使用短路运算符编辑字典

python - 在Docker中分发python源代码安全吗?

javascript - 来自 CryptoJS 和 Python Hashlib 的等效 MD5

Python __getitem__ 和 in 运算符导致奇怪的行为

轴 ('square' ) 和 set_xlim 之间的 python 相互作用

python - 初始化对象时传递方法的最佳方式是什么

python-3.x - Docker - 将 python 输出写入当前工作目录中的 csv 文件

python - PyUnicode字符串和C字符串之间的字符串转换是如何工作的?

python - 与 uwsgi 和 websockets 紧密联系