我是 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 回溯(最后一次调用):
打印(数组[i],结束=“”)
IndexError:列表索引超出范围
我如何在一行中打印整数列表(假设我的前两行代码是正确的),并且没有括号和逗号?
原文由 KimioN42 发布,翻译遵循 CC BY-SA 4.0 许可协议
你想说
语法
i in array
遍历列表的每个成员。 So,array[i]
was trying to accessarray[1]
,array[2]
, andarray[3]
, but the last of these is out of bounds (array
有索引 0、1 和 2)。您可以使用
print(" ".join(map(str,array)))
获得相同的效果。