简体   繁体   English

将字符串列表列表转换为 int 列表列表

[英]Convert list of lists of string to list of lists of int

I have read data from a comma-delimited text file( original format alpha_char,space 1,2,3,4,5,6,7, space alpha_characters newline char) and have output of [['1,2,3,4,5,6,7'],['7,5,3,9,8,2,4'], etc] ( ie lists of one string) and wish to convert these to [[1,2,3,4,5,6,7],[7,5,3,9,8,2,4], etc] ( ie lists of int).我从逗号分隔的文本文件(原始格式 alpha_char,空格 1,2,3,4,5,6,7,空格 alpha_characters 换行符)中读取数据并输出[['1,2,3,4,5,6,7'],['7,5,3,9,8,2,4'], etc] (即一个字符串的列表)并希望将它们转换为[[1,2,3,4,5,6,7],[7,5,3,9,8,2,4], etc] (即整数列表)。 I would therefore appreciate advice on how to read the data from the text file into list of lists of int or how to convert what I have, list of lists of string to list of lists of int.因此,我很感激有关如何将文本文件中的数据读取到 int 列表列表或如何将我拥有的字符串列表列表转换为 int 列表列表的建议。 I am being very stupid here, I know.我在这里很愚蠢,我知道。

Using list comprehension:使用列表理解:

>>> with open('file.txt') as f:
...     rows = [line.strip().split(',') for line in f]
...
>>> rows
[['1', '2', '3', '4', '5', '6', '7'], ['7', '5', '3', '9', '8', '2', '4']]
>>> nums = [list(map(int, row)) for row in rows]
>>> nums
[[1, 2, 3, 4, 5, 6, 7], [7, 5, 3, 9, 8, 2, 4]]

You can also use csv module :您还可以使用csv模块

>>> import csv
>>>
>>> with open('file.txt') as f:
...     reader = csv.reader(f)
...     rows = [row for row in reader]
...
>>> rows
[['1', '2', '3', '4', '5', '6', '7'], ['7', '5', '3', '9', '8', '2', '4']]

To filter numbers and convert your output, you can do the following:要过滤数字并转换输出,您可以执行以下操作:

new_list = [ [ int(x) for x in convert_list.split(",") if x.isdigit() ] for sublist in oldlist for convert_list in sublist ]

If you want to know if you have input which is not a number, you can omit the .isdigit() and use try except:如果你想知道你输入的是否不是数字,你可以省略.isdigit()并使用 try except:

try:
    [ [ int(x) for x in convert_list.split(",") ] for sublist in oldlist for convert_list in sublist ]
except ValueError:
    print("bad input")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM