简体   繁体   English

从文本文件中读取数据并使用1-liner填充列表

[英]Reading data from a text file and populate a list using a 1-liner

For solving Project Euler's problem#67 , i used below code to read data & load data in the initial list, D. 为了解决欧拉项目#67问题 ,我使用了以下代码来读取数据并将数据加载到初始列表D中。

I am wondering if all these can be done in Pythonic 1-liner 我想知道是否所有这些都可以在Pythonic 1-liner中完成

f=open("triangle.txt")
A=[]
for i in range(100):
    A.append((f.readline()).strip())

// init 
D=[]
for i in range(100):
    D.append((A[i]).split())
for i in range(100):
        for j in range(len(D[i])):
            D[i][j]= int(D[i][j])

Whereas, the data format is like this: 数据格式如下:

59
73 41
52 40 09
26 53 06 34
10 51 87 86 81
61 95 66 57 25 68
...................
.....................

Yes, by using a list comprehension (Python 2 or 3): 是的,通过使用列表理解(Python 2或3):

with open('triangle.txt') as infh:
    D = [[int(w) for w in line.split()] for line in infh]

or, if using Python 2, using map() : 或者,如果使用Python 2,则使用map()

with open('triangle.txt') as infh:
    D = [map(int, line.split()) for line in infh]

map() in Python 3 returns an iterator; Python 3中的map()返回一个迭代器; in Python 2 it returns a list and would be faster for this usecase. 在Python 2中,它返回一个列表,并且在这种情况下会更快。

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

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