For solving Project Euler's problem#67 , i used below code to read data & load data in the initial list, D.
I am wondering if all these can be done in 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):
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()
:
with open('triangle.txt') as infh:
D = [map(int, line.split()) for line in infh]
map()
in Python 3 returns an iterator; in Python 2 it returns a list and would be faster for this usecase.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.