Kim*_*N42 21 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()]
Run Code Online (Sandbox Code Playgroud)
显然它可以工作,因为当我输入'1 2 3'并做一个print(array)输出是:
[1,2,3]
但是我想在没有括号的单行中打印它,并且在数字之间有一个空格,如下所示:
1 2 3
我试过做:
for i in array:
print(array[i], end=" ")
Run Code Online (Sandbox Code Playgroud)
但是我收到一个错误:
2 3追溯(最近一次通话):
print(array [i],end ="")
IndexError:列表索引超出范围
如何在一行中打印整数列表(假设我的前两行代码是正确的),没有括号和逗号?
Nic*_*teo 29
你想说
for i in array:
print(i, end=" ")
Run Code Online (Sandbox Code Playgroud)
语法i in array遍历列表的每个成员.所以,array[i]试图访问array[1],, array[2]和array[3],但最后一个是超出界限(array有索引0,1和2).
您可以获得相同的效果print(" ".join(map(str,array))).
小智 21
是的,这在Python 3中是可能的,只需*在变量之前使用,如:
print(*list)
Run Code Online (Sandbox Code Playgroud)
这将打印由空格分隔的列表.
Cor*_*erg 13
这些都适用于Python 2.7和Python 3.x:
>>> l = [1, 2, 3]
>>> print(' '.join(str(x) for x in l))
1 2 3
>>> print(' '.join(map(str, l)))
1 2 3
Run Code Online (Sandbox Code Playgroud)
顺便说一句,array是Python中的保留字.
尝试在你的整数的str转换中使用join:
print ' '.join(str(x) for x in array)
Run Code Online (Sandbox Code Playgroud)
您有多个选项,每个选项都有不同的一般用例.
第一种方法是使用for循环,如您所述,但采用以下方式.
for value in array:
print(value, end=' ')
Run Code Online (Sandbox Code Playgroud)
您还可以str.join使用理解来使用简单,可读的单行.此方法适用于将此值存储到变量中.
print(' '.join(str(value) for value in array))
Run Code Online (Sandbox Code Playgroud)
我最喜欢的方法,但是,这是通过array作为*args,用sep的' '.但请注意,此方法仅生成printed输出,而不是可以存储到变量的值.
print(*array, sep=' ')
Run Code Online (Sandbox Code Playgroud)