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

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

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

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

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

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


当前回答

你也可以使用“+”运算符组合两个列表(比如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]

其他回答

你也可以使用“+”运算符组合两个列表(比如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]

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

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

一个略短的版本,它依赖于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的内容追加到末尾。

如果我们有如下列表:

list  = [2,2,3,4]

将它复制到另一个列表的两种方法。

1.

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

长度为1 [2,2,3,4]

2.

x = [l for l in list]
print("length is {}".format(len(x)))
for i in x:
    print(i)

长度为4 2 2 3. 4

你可以使用__add__ Magic方法:

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