Python 3.x 如何在Python中将字符串作为整数插入列表

Python 3.x 如何在Python中将字符串作为整数插入列表,python-3.x,Python 3.x,我需要将一个数字(用户输入)作为整数插入Python列表 我的代码: count = 0 list1 = [] for number in input(): if number != ' ': list1.append(int(number)) 输入:10112 输出:[1,0,1,1,1,2] 预期输出:[10,11,12]在字符串上循环(例如input()返回的字符串)将在字符串中的各个字符上循环: >>> s = 'hi guys' >&g

我需要将一个数字(用户输入)作为整数插入Python列表

我的代码:

count = 0
list1 = []
for number in input():
    if number != ' ':
        list1.append(int(number))
输入:10112

输出:
[1,0,1,1,1,2]

预期输出:
[10,11,12]
在字符串上循环(例如
input()
返回的字符串)将在字符串中的各个字符上循环:

>>> s = 'hi guys'
>>> for char in s:
...     print(char)
...
h
i

g
u
y
s
>>>
若要在“单词”(即用空格分隔的子字符串)上循环,您需要将用户的输入改为:

>>> s = 'hi guys'
>>> words = s.split()
>>> words
['hi', 'guys']
>>> for word in words:
...     print(word)
...
hi
guys
>>>
因此,在您的情况下,这将是:

for number in input().split():
    list1.append(int(number))

我们可以留下
if number!='':
out,因为
split()
已经去掉了所有空格,只返回一个数字列表。

您应该使用
split
方法将值拆分为带字符串的列表:

str_nums = input.split() #will give ['10','11','12'] 
然后

您还可以一起使用和拆分

inp = "10 11 12"
print(list(map(int,inp.split(" "))))

#Output
[10,11,12]

给你

input_array = []

c_input = input('please enter the input\n')

for item in c_input.split():

    input_array.append(int(item))

print (input_array)
输入:-11123456

输出:-[1,11,23,23456]


我希望您觉得它很有用

请选择任何答案,就像您得到了答案一样。@yëShñipün确保它是否解决了您的问题:)这并不能解决OP的问题。当然,您可以使用
list(map(int,s))
而不是
来执行
循环,但这与OP的问题
split()
完全无关。如果您像OP一样使用
list(map(int,s))
,而不使用
split()
@MarkusMeskanen,很抱歉我不明白,但这并不能解决问题。@Bhansa您展示的代码片段确实解决了问题,但不是因为
map()
和列表理解,只是因为他们调用了
str.split()
。你的答案甚至没有提到
split()
,但听起来像是使用
map()
,或者理解是解决问题的方法,而实际上他们与此无关。“使用
split()
”是正确答案。谢谢@Markus,明白了。我的回答更多的是关于获得输出。
print([int(i) for i in input().split()])
input_array = []

c_input = input('please enter the input\n')

for item in c_input.split():

    input_array.append(int(item))

print (input_array)