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

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

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

我的想法是在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

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

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


当前回答

你可能想要

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)

其他回答

你可能想要

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)

看看itertools。Chain提供了一种快速的方法,可以将许多小列表作为一个大列表(或至少作为一个大iterable),而不复制小列表:

>>> 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()

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

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

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

这对你要做的事情来说似乎很合理。

一个略短的版本,它依赖于Python来完成更多的繁重工作,可能是:

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

    ....

(如果line中有"string",则list1中的line为True)遍历list并在找到匹配时发出True。any()在找到第一个True元素时使用短路求值返回True。List2.extend()将list1的内容追加到末尾。

使用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循环”和优雅的编码模式:)