Take the content of a list and append it to another list

后端 未结 7 1697
死守一世寂寞
死守一世寂寞 2020-12-07 08:55

I am trying to understand if it makes sense to take the content of a list and append it to another list.

I have the first list created through a loop function, that

相关标签:
7条回答
  • 2020-12-07 09:08

    That seems fairly reasonable for what you're trying to do.

    A slightly shorter version which leans on Python to do more of the heavy lifting might be:

    for logs in mydir:
    
        for line in mylog:
            #...if the conditions are met
            list1.append(line)
    
        if any(True for line in list1 if "string" in line):
            list2.extend(list1)
        del list1
    
        ....
    

    The (True for line in list1 if "string" in line) iterates over list and emits True whenever a match is found. any() uses short-circuit evaluation to return True as soon as the first True element is found. list2.extend() appends the contents of list1 to the end.

    0 讨论(0)
  • 2020-12-07 09:11

    Take a look at itertools.chain for a fast way to treat many small lists as a single big list (or at least as a single big iterable) without copying the smaller lists:

    >>> import itertools
    >>> p = ['a', 'b', 'c']
    >>> q = ['d', 'e', 'f']
    >>> r = ['g', 'h', 'i']
    >>> for x in itertools.chain(p, q, r):
            print x.upper()
    
    0 讨论(0)
  • 2020-12-07 09:13

    You can also combine two lists (say a,b) using the '+' operator. For example,

    a = [1,2,3,4]
    b = [4,5,6,7]
    c = a + b
    
    Output:
    >>> c
    [1, 2, 3, 4, 4, 5, 6, 7]
    
    0 讨论(0)
  • 2020-12-07 09:15

    Using the map() and reduce() built-in functions

    def file_to_list(file):
         #stuff to parse file to a list
         return list
    
    files = [...list of files...]
    
    L = map(file_to_list, files)
    
    flat_L = reduce(lambda x,y:x+y, L)
    

    Minimal "for looping" and elegant coding pattern :)

    0 讨论(0)
  • 2020-12-07 09:24

    If we have list like below:

    list  = [2,2,3,4]
    

    two ways to copy it into another list.

    1.

    x = [list]  # x =[] x.append(list) same 
    print("length is {}".format(len(x)))
    for i in x:
        print(i)
    
    length is 1
    [2, 2, 3, 4]
    

    2.

    x = [l for l in list]
    print("length is {}".format(len(x)))
    for i in x:
        print(i)
    
    length is 4
    2
    2
    3
    4
    
    0 讨论(0)
  • 2020-12-07 09:27

    You probably want

    list2.extend(list1)
    

    instead of

    list2.append(list1)
    

    Here's the difference:

    >>> a = range(5)
    >>> b = range(3)
    >>> c = range(2)
    >>> b.append(a)
    >>> b
    [0, 1, 2, [0, 1, 2, 3, 4]]
    >>> c.extend(a)
    >>> c
    [0, 1, 0, 1, 2, 3, 4]
    

    Since list.extend() accepts an arbitrary iterable, you can also replace

    for line in mylog:
        list1.append(line)
    

    by

    list1.extend(mylog)
    
    0 讨论(0)
提交回复
热议问题