【问题标题】:Error when reading from input line in Python [duplicate]从 Python 中的输入行读取时出错 [重复]
【发布时间】:2018-06-20 19:32:55
【问题描述】:

使用python3

import sys

input = sys.stdin.read() 
tokens = input.split()
a = int(tokens[0]) 
b = int(tokens[1]) 

print(a + b)

我正在尝试用 Python 编译这个简单的代码。但是它给了我索引错误:列表索引超出范围。我只需要编译这段代码,然后在输入行输入 2 位数字。

【问题讨论】:

  • 展示你如何运行它。这里没有错误,Python 无法按照您的意思编译。

标签: python python-3.x


【解决方案1】:

.split() 在空间上分裂。如果您的数字之间没有空格,它将不起作用,因为它们都将在一个元素中 (tokens[0])

演示:

>>> '12'.split()
['12']
>>> '1 2'.split()
['1', '2']

【讨论】:

    【解决方案2】:

    试试这个:

    import sys
    
    inputed = sys.stdin.read() 
    tokens = str(inputed)
    a = int(tokens[0]) 
    b = int(tokens[1]) 
    
    print(a + b)
    

    【讨论】:

      猜你喜欢
      • 2023-01-27
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多