【问题标题】:how to create a list of integers from a text file with multiple lines?如何从具有多行的文本文件创建整数列表?
【发布时间】:2020-07-22 22:49:24
【问题描述】:

我需要编写一个程序来读取文本文件并返回文件中数字的中位数。我想我很清楚如何解决这个问题,但是在运行我的程序时遇到了 AttributeError。

我的问题是:如何为文本文件中的数字制作一个列表?共有 15 个数字,在文件中分为 5 行:

10 20 30
40 50 60
90 80 70
11 22 13
14 14 20

我想创建一个列表是:

num_list = fv.readlines()
num_list = num_list.split()

我认为这会读取文件的所有行,然后我可以使用 split 函数创建一个数字列表。现在我得到了一个 AttributeError: 'list' object has no attribute 'split',我不确定该怎么做。

【问题讨论】:

  • num_list = [int(x) for x in fv.read().split()].
  • 感谢您的回复,终于成功了!

标签: python python-3.x list file


【解决方案1】:

如果没有可靠的预期结果,我假设您希望将所有数字放在一个列表中。

您可以创建一个空列表,然后在循环文件时使用list.extend。不过,您需要将它们转换为 int 。 map 非常适合:

num_list = []
with open('filename.txt') as fv:
    for row in fv:
        num_list.extend(map(int, row.split()))

您可以更有效地使用re

import re

with open('filename.txt') as fv:
    num_list = list(map(int, re.findall('\d+', fv.read())))

结果(以上两者)将是:

[10, 20, 30, 40, 50, 60, 90, 80, 70, 11, 22, 13, 14, 14, 20]

否则在子列表中按行/行:

with open('filename.txt') as fv:
    num_list = [list(map(int, row.split())) for row in fv]

结果:

[[10, 20, 30], [40, 50, 60], [90, 80, 70], [11, 22, 13], [14, 14, 20]]

【讨论】:

    【解决方案2】:

    我认为这就是你想要做的:

    lines = fv.readlines()
    num_list = []
    
    for line in lines:
        num_list.extend(line.split(' '))
    
    num_list = [int(num.strip()) for num in num_list]
    

    【讨论】:

      【解决方案3】:

      我的答案肯定是更长的版本,但是...

      text = open('numbers.txt', 'r')
      string = text.read()
      string = string.replace('\n', ' ')
      numbers = string.split(' ')
      text.close()
      
      #Print to see the result
      print(numbers)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多