Python:使用列表的列表解析

pvabu6sv  于 2023-05-02  发布在  Python
关注(0)|答案(4)|浏览(157)

如何在列表解析中编写以下代码?

with open('some_file.txt', 'r') as f:
    lines = f.readlines()

lines = [line.strip('\n') for line in lines]
list_of_lists = [[int(elm) for elm in line.split(' ')] for line in lines]

我的文件看起来像这样:

3 8 6 9 4
4 3 0 8 6
2 8 3 6 9
3 7 9 0 3

这意味着:

grid = '3 8 6 9 4\n4 3 0 8 6\n2 8 3 6 9\n3 7 9 0 3'
piwo6bdm

piwo6bdm1#

在这里尝试一下,首先拆分每行,你会得到一个字符串形式的数字列表,所以可以使用map函数将其更改为int

with open('file.txt', 'r') as f:
    k = [list(map(int,i.split())) for i in f.readlines()]
    print(k)
nbnkbykc

nbnkbykc2#

int不关心换行符,因此您可以跳过剥离这些字符。

>>> fake_file = '3 8 6 9 4\n4 3 0 8 6\n2 8 3 6 9\n3 7 9 0 3\n'.splitlines()
>>> [[int(x) for x in line.split()] for line in fake_file]
[[3, 8, 6, 9, 4], [4, 3, 0, 8, 6], [2, 8, 3, 6, 9], [3, 7, 9, 0, 3]]

请注意,pandasnumpy提供了用于阅读数据的高级功能,例如:例如numpy.loadtxtpandas.read_csv

wgx48brx

wgx48brx3#

您不需要分别应用str.stripstr.split。相反,将它们合并到一个操作中。列表解析是通过定义一个列表元素,然后在for循环上进行迭代来构造的。
还要注意,没有参数的str.strip将处理\n以及空白。类似地,不带参数的str.split将被空格分隔。

from io import StringIO

x = StringIO("""3 8 6 9 4
4 3 0 8 6
2 8 3 6 9
3 7 9 0 3""")

# replace x with open('some_file.txt', 'r')
with x as grid:
    list_of_lists = [[int(elm) for elm in line.strip().split()] for line in grid]

结果:

print(list_of_lists)

[[3, 8, 6, 9, 4],
 [4, 3, 0, 8, 6],
 [2, 8, 3, 6, 9],
 [3, 7, 9, 0, 3]]

使用内置插件,使用map稍微更有效:

list_of_lists = [list(map(int, line.strip().split())) for line in grid]
bvuwiixz

bvuwiixz4#

你可以使用Map功能

grid = open('some.txt', 'r')
lines = [line.strip('\n') for line in grid]

list_of_lists = []

f = lambda line: [int(elm) for elm in line.split(' ')]
list_of_lists = map(f, lines)
print(list_of_lists)

或者你可以实现它更短

f = lambda line: map(int, line.split(' '))
list_of_lists = map(f, lines)
print(list_of_lists)

相关问题