我尝试使用list comprehension来替换for循环.
原始文件是
2 3 4 5 6 3 1 2 2 4 5 5 1 2 2 2 2 4
for循环
line_number = 0 for line in file: line_data = line.split() Cordi[line_number, :5] = line_data line_number += 1
输出是
[[2 3 4 5 6 3] [1 2 2 4 5 5] [1 2 2 2 2 4]]
如果使用列表理解,我可以想到的是(我必须将数据类型更改为int,因此可以在程序的后续部分中绘制)
Cordi1= [int(x) for x in line.split() for line in data]
但输出是
[1, 1, 1]
但line.split() for line in data
实际上是一个列表,如果我尝试
Cordi1 = [int(x) for x in name of the list]
它有效,为什么会这样?
您已经交换了循环的顺序; 它们应该按照从左到右的嵌套方式进行排序:
[int(x) for line in data for x in line.split()]
这data
首先循环,然后对于每次line
迭代,迭代line.split()
生成x
.然后,您可以从中生成一个整数的平面列表.
但是,由于您正在尝试构建列表列表,因此需要将列表推导嵌套在另一个列表中:
Cordi1 = [[int(i) for i in line.split()] for line in data]
演示:
>>> data = '''\ ... 2 3 4 5 6 3 ... 1 2 2 4 5 5 ... 1 2 2 2 2 4 ... '''.splitlines() >>> [int(x) for line in data for x in line.split()] [2, 3, 4, 5, 6, 3, 1, 2, 2, 4, 5, 5, 1, 2, 2, 2, 2, 4] >>> [[int(i) for i in line.split()] for line in data] [[2, 3, 4, 5, 6, 3], [1, 2, 2, 4, 5, 5], [1, 2, 2, 2, 2, 4]]
如果你想要一个多维的numpy数组,你可以将上面的数据直接转换为数组,或者从数据创建一个数组,然后重塑:
>>> import numpy as np >>> np.array([[int(i) for i in line.split()] for line in data]) array([[2, 3, 4, 5, 6, 3], [1, 2, 2, 4, 5, 5], [1, 2, 2, 2, 2, 4]]) >>> np.array([int(i) for line in data for i in line.split()]).reshape((3, 6)) array([[2, 3, 4, 5, 6, 3], [1, 2, 2, 4, 5, 5], [1, 2, 2, 2, 2, 4]])