Python 列表理解替换二维矩阵中的循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25345770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
list comprehension replace for loop in 2D matrix
提问by rankthefirst
I try to use list comprehension to replace the for loop.
我尝试使用列表理解来替换 for 循环。
original file is
原始文件是
2 3 4 5 6 3
1 2 2 4 5 5
1 2 2 2 2 4
for loop
for循环
line_number = 0
for line in file:
line_data = line.split()
Cordi[line_number, :5] = line_data
line_number += 1
output is
输出是
[[2 3 4 5 6 3]
[1 2 2 4 5 5]
[1 2 2 2 2 4]]
if use list comprehension instead, for what I can think of is (I have to change the data type to int, so it can be plotted in later part of the program)
如果改用列表理解,我能想到的是(我必须将数据类型更改为 int,以便可以在程序的后面部分绘制)
Cordi1= [int(x) for x in line.split() for line in data]
but the output is
但输出是
[1, 1, 1]
but line.split() for line in datais actually a list, and if I try
但line.split() for line in data实际上是一个列表,如果我尝试
Cordi1 = [int(x) for x in name of the list]
it works, why this happens?
它有效,为什么会发生这种情况?
采纳答案by Martijn Pieters
You have the order of your loops swapped; they should be ordered in the same way they would be nested, from left to right:
您交换了循环的顺序;它们的顺序应该与嵌套的方式相同,从左到右:
[int(x) for line in data for x in line.split()]
This loops over datafirst, then for each lineiteration, iterates over line.split()to produce x. You then produce one flatlist of integers from these.
这data首先循环,然后对于每次line迭代,迭代line.split()生成x。然后,您可以从中生成一个平面整数列表。
However, since you are trying to build a list of lists, you need to nest a list comprehension inside another:
但是,由于您正在尝试构建列表列表,因此需要将列表理解嵌套在另一个列表中:
Cordi1 = [[int(i) for i in line.split()] for line in data]
Demo:
演示:
>>> 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]]
If you wanted a multidimensional numpy array from this, you can either convert the above directly to an array or create an array from the data then reshape:
如果您想要一个多维 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]])

