【问题标题】:Change a list of list of str to list of list of int将 str 列表更改为 int 列表列表
【发布时间】:2014-12-11 22:23:03
【问题描述】:

我正在尝试读取 CSV 文件并将数据作为整数列表返回。 CSV 文件为 6 列宽和 2 行。使用 Python 3.4。

它总是以 strs 列表的形式出现。搜索 StackOverflow 和 Google 显示了 7 种不同的方法来做到这一点,但都不起作用。这些显示在我尝试过的代码下方。

import csv
b = []
with open('C:\Python34\DataforProgramstorun\\csv data6x2.csv') as f:
reader = csv.reader(f)
for row in reader :
    b.append(row) # this gives me a list of list each element a csv str from print (b)

print (b)

结果是:

[['2', '5', '15', '17', '19', '20'], ['6', '8', '14', '18', '21', '30']]

我希望它是:

[[2, 5, 15, 17, 19, 20], [6, 8, 14, 18, 21, 30]]

以下都不起作用:

  1. [ int(x) for y in b for x in y.split() ] #builtins.AttributeError: 'list' object has no attribute 'split'

  2. [int(x) for x in ' '.join(b).split ()] #builtins.TypeError: sequence item 0: expected str instance, list found

  3. import itertools as it; new =list(it.imap(int,b)) #builtins.AttributeError: 'module' object has no attribute 'imap'

  4. for i in range (0,len(b)): b[i] = int (b[i]) #builtins.TypeError: int() argument must be a string or a number, not 'list'

  5. results = b; results = [int(i) for i in results] ##builtins.TypeError: int() argument must be a string or a number, not'list'

  6. b = list(map(int,b)) #builtins.TypeError: int() argument must be a string or a number, not 'list'

  7. [int(i) for i in b] #builtins.TypeError: int() argument must be a string or a number, not 'list'

【问题讨论】:

  • 在 #3 上,Python 3 没有 itertools.imap,因为 map 现在是一个迭代器。在其他大多数情况下,请注意您需要将它们应用到 b 中的每个列表,而不是 b 本身。

标签: string list csv python-3.x


【解决方案1】:
>>> lst = [['2', '5', '15', '17', '19', '20'], ['6', '8', '14', '18', '21', '30']]
>>> [[int(x) for x in inner] for inner in lst]
[[2, 5, 15, 17, 19, 20], [6, 8, 14, 18, 21, 30]]

您尝试过的所有解决方案的问题在于,您只能深入一层。因此,您确实考虑了外部列表,但随后尝试直接使用内部列表,这通常会失败。要解决这个问题,您需要直接处理 inner 列表。你也可以这样解决:

for i, sublist in enumerate(b):
    b[i] = [int(x) for x in sublist]

除了[int(x) for x in sublist],您还可以使用许多其他解决方案之一将(子)列表中的所有字符串转换为整数,例如list(map(int, sublist))

【讨论】:

  • 谢谢,除了解决方案,您还告诉我为什么我的不工作。非常感谢
猜你喜欢
  • 2021-12-24
  • 2021-12-02
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 2018-08-30
  • 2018-09-29
  • 2011-03-18
  • 1970-01-01
相关资源
最近更新 更多