list comprehension替换2D矩阵中的循环 [英] list comprehension replace for loop in 2D matrix

查看:189
本文介绍了list comprehension替换2D矩阵中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用list comprehension来替换for循环。

I try to use list comprehension to replace the for loop.

原始文件是

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,因此可以在程序的后续部分中绘制)

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)

Cordi1= [int(x) for x in line.split() for line in data]

但输出

[1, 1, 1]

line.split()表示数据中的行实际上是一个列表,如果我尝试

but line.split() for line in data is actually a list, and if I try

Cordi1 = [int(x) for x in name of the list]

它有效,为什么会发生这种情况?

it works, why this happens?

推荐答案

您已经交换了循环的顺序;它们的排序方式应该是从左到右嵌套的方式:

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()]

这循环超过数据首先,然后对于每个迭代,迭代 line.split()以生成 X 。然后,您可以从这些生成一个 flat 整数列表。

This loops over data first, then for each line iteration, iterates over line.split() to produce x. You then produce one flat list of integers from these.

但是,由于您正在尝试构建列表列表,因此需要嵌套另一个列表理解:

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]

演示:

>>> 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数组,您可以将上面的数据直接转换为数组或从数据创建数组然后重塑:

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:

>>> 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]])

这篇关于list comprehension替换2D矩阵中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆