python - 我们如何在一行中使用空格输入原始输入,然后将它们转换为整数并将它们添加到列表中?

标签 python string python-2.7

我的代码:

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/

相关文章:

arrays - 如何替换字符串中的单个字符?

PHP 检查一个字符串中的所有字符是否都是中文

c++ - 一个字符串的 Cout 给出了一个错误并且很难有一些洞察力帮助吗?

python - 为什么 str(float) 在 Python 3 中返回的位数比 Python 2 多?

Python复杂字典排序

python - 安装 pywin32 - win32api.pyd 权限被拒绝

Python字典矩阵 "representation"

python - 我一直在我的 settings.py 文件中收到错误 "ModuleNotFoundError: No module named ' 环境“。我已经在我的 python shell 中安装了依赖项

python - 从类方法创建新的类实例

javascript - 如何从动态更新的网页中提取数据