简体   繁体   English

如何创建列表列表

[英]how to create a list of lists

My Python code generates a list everytime it loops:我的 Python 代码每次循环时都会生成一个列表:

list = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)

But I want to save each one - I need a list of lists right?但我想保存每一个 - 我需要一个列表,对吗?

So I tried:所以我试过:

list[i] = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)

But Python now tells me that "list" is not defined.但是 Python 现在告诉我没有定义“列表”。 I'm not sure how I go about defining it.我不确定我是如何定义它的。 Also, is a list of lists the same as an array??另外,列表列表与数组相同吗??

Thank you!谢谢!

You want to create an empty list, then append the created list to it.您想创建一个空列表,然后将创建的列表附加到它。 This will give you the list of lists.这将为您提供列表列表。 Example:例子:

>>> l = []
>>> l.append([1,2,3])
>>> l.append([4,5,6])
>>> l
[[1, 2, 3], [4, 5, 6]]

Use append method, eg:使用 append 方法,例如:

lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)

Create your list before your loop, else it will be created at each loop.在循环之前创建您的列表,否则它将在每个循环中创建。

>>> list1 = []
>>> for i in range(10) :
...   list1.append( range(i,10) )
...
>>> list1
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [5, 6, 7, 8, 9], [6, 7, 8, 9], [7, 8, 9], [8, 9], [9]]

First of all do not use list as a variable name- that is a builtin function.首先不要使用list作为变量名——这是一个内置函数。

I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-我不是很清楚你在问什么(多一点上下文会有所帮助),但也许这会有所帮助-

my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))

That will create a list (a type of mutable array in python) called my_list with the output of the np.getfromtext() method in the first 2 indexes.这将创建一个名为my_list的列表(python 中的一种可变数组np.getfromtext() ,并在前 2 个索引中使用np.getfromtext()方法的输出。

The first can be referenced with my_list[0] and the second with my_list[1]第一个可以用my_list[0]引用,第二个可以用my_list[1]引用

Just came across the same issue today...今天刚遇到同样的问题...

In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list.为了创建列表列表,您首先必须将数据、数组或其他类型的变量存储到列表中。 Then, create a new empty list and append to it the lists that you just created.然后,创建一个新的空列表并将您刚刚创建的列表附加到它。 At the end you should end up with a list of lists:最后你应该得到一个列表列表:

list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)

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

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