how to create a list of lists

后端 未结 5 2080
孤独总比滥情好
孤独总比滥情好 2020-12-16 20:30

My Python code generates a list everytime it loops:

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


        
相关标签:
5条回答
  • 2020-12-16 20:54

    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]]
    
    0 讨论(0)
  • 2020-12-16 20:55

    Use append method, eg:

    lst = []
    line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
    lst.append(line)
    
    0 讨论(0)
  • 2020-12-16 20:56

    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]]
    
    0 讨论(0)
  • 2020-12-16 20:57

    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]

    0 讨论(0)
  • 2020-12-16 21:16

    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)
    
    0 讨论(0)
提交回复
热议问题