【问题标题】:How to put a group of integers in a row in a text file into a list?如何将文本文件中一行中的一组整数放入列表中?
【发布时间】:2021-11-24 21:36:46
【问题描述】:

我有一个主要由数字组成的文本文件,如下所示:

3  011236547892X
9  02321489764 Q
4  031246547873B

我想将以下每个(空格 5 到 14(从零开始计数))提取到一个列表中:

1236547892
321489764 
1246547873

(请注意:每个“数字”长度为 10 个“字符” - 第二行末尾有一个空格。)

然后对每个列表的内容进行分析。

我有无数个版本,但我认为我最接近:

with open('k_d_m.txt') as f:
        for line in f:
            range = line.split()
            num_lst = [x for x in range(3,10)]

print(num_lst)

但是我有:TypeError: 'list' object is not callable

什么是最好的前进方式?

我想用 num_lst 做的事情如下:

num_lst = list(map(int, str(num)))

打印(num_lst)

第 n = 2

odd_total = sum(num_lst[0::nth]) even_total = sum(num_lst[1::nth]) 打印(奇数) 打印(偶数)

如果odd_total - even_total == 0 或odd_total - even_total == 11: print("号码没问题") 别的: print("号码不对")

【问题讨论】:

标签: python text split list-comprehension


【解决方案1】:

使用简单的切片:

with open('k_d_m.txt') as f:
    num_lst = [x[5:15] for x in f]

回复评论:

with open('k_d_m.txt') as f:
    for line in f:
        num_lst = list(line[5:15])
        print(num_lst)

【讨论】:

  • 嗨,Mozway,不幸的是,所有数字都包含在一个列表中。我需要每个数字,只有那个数字在 num_lst 中。然后我对数字进行分析,然后进行下一个
  • 您能否编辑您的问题以提供预期的输出(作为有效的 python 对象)?
  • 嗨 Mozway,读完一行后,我想要一个这样的列表:num_lst = [1, 2, 3, 6, 5, 4, 7, 8, 9, 2]跨度>
  • 我将其用作以下内容的输入: num_lst = list(map(int, str(num))) print(num_lst) nth = 2 odd_total = sum(num_lst[0::nth]) even_total = sum(num_lst[1::nth]) print(odd_total) print(even_total) ifodd_total - even_total == 0 或odd_total - even_total == 11: print("数字没问题") else: print("号码不对”)
  • 评论不好贴多行代码,请编辑问题。无论如何,请检查我的更新以了解基本原理
【解决方案2】:

首先,您不应该将变量命名为range,因为range() 函数已经使用了它。您可以使用 string[5:15] 轻松获取字符串的第 5 到第 14 个字符。试试这个:

num_lst = []
with open('k_d_m.txt') as f:
    for line in f:
        num_lst.append(line[5:15])
print(num_lst)

【讨论】:

  • 嗨,Erik,不幸的是,所有数字都包含在一个列表中。我需要每个数字,只有那个数字在 num_lst 中。然后我对 number / num_lst 进行分析,然后进行下一个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 2012-08-29
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 2011-03-04
相关资源
最近更新 更多