我的代码:
number = raw_input().split()
# I can't get a line here to do the trick
a = list()
a.append(number)
我需要做的就是在一行中输入 2 个整数,用空格分隔。然后将它们作为整数输入到 Python 列表中,然后将元素添加回结果变量。
最佳答案
这会拆分您在空格处输入的所有内容,并尝试将每个条目转换为整数:
numbers = [int(x) for x in raw_input().split()]
这是一个列表理解。它与这段代码的作用相同:
numbers = []
for x in raw_input().split():
numbers.append(int(x))
列表理解更短。如果您需要处理潜在的异常并且您的代码变得更加复杂,则循环可能更合适。
进一步改进 - 错误处理
用户输入错误数据的可能性始终存在。
def get_numbers(count=2):
"""Get `count` integers from one line of user input.
"""
numbers = []
msg = 'Please enter {} integers separated by space: '.format(count)
for entry in raw_input(msg).split():
try:
numbers.append(int(entry))
except ValueError:
print('Found bad value: {}.'.format(entry))
return get_numbers()
if len(numbers) != count:
print('Need to enter exactly {} numbers. '
'Found: {}.'.format(count, len(numbers)))
return get_numbers()
return numbers
my_two_numbers = get_numbers()
关于python - 我们如何在一行中使用空格输入原始输入,然后将它们转换为整数并将它们添加到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30151559/