简体   繁体   English

一行中的Python 2d列表生成器

[英]Python 2d list generator in one line

I have a matrix of numbers in a file (distances between cities for solving TSP). 我在文件中有一个数字矩阵(用于解决TSP的城市之间的距离)。 I load it up into a list. 我将其加载到列表中。 After that each row in my list looks like this: 之后,列表中的每一行如下所示:

' 9999    3    5   48   48    8    8    5    5    3    3    0    3    5    8    8    5\n'

The number of whitespaces between numbers may be different on each line. 每行上数字之间的空格数可能不同。 Now I just want to convert it to a list of lists of ints/floats. 现在,我只想将其转换为整数/浮点数列表。 I got that with a loop: 我有一个循环:

matrix = []
for row in lines[begin:end]:
    matrix.append([float(x) for x in row.split()])

It works just fine. 它工作正常。 I am just curious if I can use a generator here (like I use it in loop), but not in loop, but in one line. 我很好奇我是否可以在这里使用生成器(就像我在循环中使用它),但不是在循环中,而是在一行中。 I tried something like [float(x) for x in [y.split() for y in lines[begin:end]]] , but it says: 我尝试了类似[float(x) for x in [y.split() for y in lines[begin:end]]] ,但是它说:

float() argument must be a string or a number, not 'list'

So can it be solved like in one line, or should I leave it in loop? 那么它可以像一行一样解决吗,还是应该让它循环处理?

You could use the following list comprehension 您可以使用以下列表理解

matrix = [[float(i) for i in row.split()] for row in lines]

But for this particular case, it would be much faster to use numpy.genfromtxt 但是对于这种特殊情况,使用numpy.genfromtxt会更快

import numpy as np
matrix = np.genfromtxt('your_file', delimeter=' ')

Of course you can. 当然可以。

my_list = [' 9999    3    5   48   48    8    8    5    5    3    3    0    3    5    8    8    5\n', 
           ' 3    12    5   48   48    8    8    5    5    3    3    0    3    5    8    8    5\n']

gen = (list(map(float, f.split())) for f in my_list)

You can now iterate over gen . 现在,您可以遍历gen

For example: 例如:

for i in gen:
  print(i)
  • First iteration returns: [9999.0, 3.0, 5.0, 48.0, 48.0, 8.0, ...] 第一次迭代返回: [9999.0, 3.0, 5.0, 48.0, 48.0, 8.0, ...]
  • Second one: [3.0, 12.0, 5.0, 48.0, 48.0, 8.0, ...] 第二个: [3.0, 12.0, 5.0, 48.0, 48.0, 8.0, ...]

I am assuming that by generator you actually mean generator by the way and not list-comprehension . 我假设使用generator实际上是指generator ,而不是list-comprehension If that is not the case, the answer by @Cody is the way to go. 如果不是这种情况,则@Cody的答案是正确的方法。

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

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