我是 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/