【问题标题】:How to read integers from a file in Python [duplicate]如何从 Python 中的文件中读取整数 [重复]
【发布时间】:2020-08-07 00:16:00
【问题描述】:

所以我有一个看起来像这样的文件

2
3
1  2  3  4  5  6

所以我需要在三个单独的变量中读取这个文件。对于前两个我使用这样的东西:

guests = int(input_file.readline())
length = int(input_file.readline())

但是对于第三行我需要一个列表,如何将其转换为整数,我试过这个:

sticks = input_file.readline()
sticks = [int(i) for i in sticks]

但它给了我一个错误:invalid literal for int() with base 10

【问题讨论】:

  • sticks.split()?
  • ticks = [int(i) for i in input_file.readline().split()]

标签: python python-3.x


【解决方案1】:

你需要使用split()来读取一行中的多个整数

sticks = [int(i) for i in sticks.split()]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-18
    • 2018-11-12
    • 2018-05-14
    • 2019-02-19
    • 2021-05-14
    • 1970-01-01
    • 2018-01-26
    • 2021-08-19
    相关资源
    最近更新 更多