【问题标题】:converting each element from string to int in nested list in python [duplicate]在python的嵌套列表中将每个元素从字符串转换为int [重复]
【发布时间】:2018-05-09 16:36:43
【问题描述】:

我在 python 中有嵌套列表的数据,其中一部分看起来像:

data = [['214', '205', '0', '14', '710', '1813494849', '0'], ['214', '204', '0', '30', '710', '1813494856', '0'], ['214', '204', '0', '34', '710', '1813494863', '0'], ['213', '204', '0', '35', '710', '1813494870', '0'], ['213', '203', '0', '35', '710', '1813494877', '0']]

在使用几种方法转换数据时:

1.

 new_data_list = [[int(x) for x in list] for list in data]
  1. list=[]
    for i in range(0,len(data)):
        list.append([])
        for j in range(0,len(data[i])):
            b=int(data[i][j])
            list[i].append(b)
    

    我收到错误消息:

ValueError: int() 以 10 为底的无效文字:''

我的数据列表中没有非数字数据。但是标题可能有一些东西,比如一个空标题被视为非数字值,因为我从 csv 创建了一个数据列表。

我想知道一种有效的方法,可以将列表的每个元素转换为 int,同时保留数据多列表。

【问题讨论】:

  • 旁注:从不 shadow 内置 list,例如请改用Llist_

标签: python python-3.x python-2.7 data-structures nested-lists


【解决方案1】:

为每个嵌套列表中的每个项目调用int

new_list = [[int(x) for x in lst] for lst in nested]

或者使用map:

new_list = [list(map(int, lst)) for lst in nested]

【讨论】:

  • 我试过了,但它显示了这个错误:ValueError: invalid literal for int() with base 10: ''
  • @TheNoviceProgrammer 看起来您的输入中有一个非数字值。您应该在问题中提到这一点。那么现在,您希望如何处理非数字值?
  • 我的数据中没有非数字值。我认为这可能是我在列表中不可见的标题,因为我使用 readcsv 创建了数据列表
  • @TheNoviceProgrammer in data 在问题中,没有非数字值,你不应该得到任何ValueError
【解决方案2】:

简洁的一个是:

x = ['123', '12', '5']
r = list(map(int, x))
print(r)
>[123, 12, 5]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-07
    • 2017-09-20
    • 2014-06-16
    • 2019-12-07
    • 1970-01-01
    • 2016-02-08
    • 2020-07-12
    • 1970-01-01
    相关资源
    最近更新 更多