Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a list of lists

Tags:

python

list

My Python code generates a list everytime it loops:

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. I'm not sure how I go about defining it. Also, is a list of lists the same as an array??

Thank you!

like image 327
user1551817 Avatar asked Sep 06 '12 04:09

user1551817


4 Answers

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]]
like image 179
Roger Allen Avatar answered Oct 23 '22 10:10

Roger Allen


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]]
like image 26
Zulu Avatar answered Oct 23 '22 10:10

Zulu


Use append method, eg:

lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)
like image 29
fabiocerqueira Avatar answered Oct 23 '22 08:10

fabiocerqueira


First of all do not use list as a variable name- that is a builtin function.

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.

The first can be referenced with my_list[0] and the second with my_list[1]

like image 3
tMC Avatar answered Oct 23 '22 10:10

tMC