我试图理解它是否有意义,采取一个列表的内容,并将其附加到另一个列表。

我通过一个循环函数创建了第一个列表,它将从文件中获取特定的行,并将它们保存在一个列表中。

然后使用第二个列表保存这些行,并在另一个文件上开始一个新的循环。

我的想法是在for循环完成后获取列表,将其转储到第二个列表中,然后开始一个新的循环,将第一个列表的内容再次转储到第二个列表中,但要追加它,因此第二个列表将是在我的循环中创建的所有较小列表文件的总和。只有在满足某些条件时,才需要添加列表。

它看起来像这样:

# This is done for each log in my directory, i have a loop running
for logs in mydir:

    for line in mylog:
        #...if the conditions are met
        list1.append(line)

    for item in list1:
        if "string" in item: #if somewhere in the list1 i have a match for a string
            list2.append(list1) # append every line in list1 to list2
            del list1 [:] # delete the content of the list1
            break
        else:
            del list1 [:] # delete the list content and start all over

这有意义吗,还是我应该走另一条路?

我需要一些有效的,不会占用太多的周期,因为日志的列表很长,每个文本文件是相当大的;所以我认为这些清单可以满足这个目的。


当前回答

使用map()和reduce()内置函数

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)

最小的“for循环”和优雅的编码模式:)

其他回答

使用map()和reduce()内置函数

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)

最小的“for循环”和优雅的编码模式:)

你也可以使用“+”运算符组合两个列表(比如a,b)。 例如,

a = [1,2,3,4]
b = [4,5,6,7]
c = a + b

Output:
>>> c
[1, 2, 3, 4, 4, 5, 6, 7]

你可以使用__add__ Magic方法:

a = [1,2,3]
b = [4,5,6]
c = a.__add__(b)
Output:
>>> c
[1,2,3,4,5,6]

你可能想要

list2.extend(list1)

而不是

list2.append(list1)

区别在于:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = [7, 8, 9]
>>> b.append(a)
>>> b
[4, 5, 6, [1, 2, 3]]
>>> c.extend(a)
>>> c
[7, 8, 9, 1, 2, 3]

因为list.extend()接受任意可迭代对象,所以也可以替换

for line in mylog:
    list1.append(line)

by

list1.extend(mylog)

你可以简单地连接两个列表,例如:

list1 = [0, 1]
list2 = [2, 3]
list3 = list1 + list2

print(list3)
>> [0, 1, 2, 3]