python - 获取列表的内容并将其附加到另一个列表

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

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

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

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

通过

list1.extend(mylog)

https://stackoverflow.com/questions/8177079/

相关文章:

linux - 如何请求文件但不使用 Wget 保存?

python - 获取文件的最后n行,类似于tail

python - 什么是 "first-class"对象?

bash - 为什么 $$ 返回与父进程相同的 id?

python - Python 2 如何比较字符串和整数?为什么列表比较大于数字,而元组大于列表?

linux - 省略任何 Linux 命令输出的第一行

python - 如何在不破坏默认行为的情况下覆盖 __getattr__?

c - Linux中的itoa函数在哪里?

mysql - 如何测试MySQL在哪个端口上运行以及是否可以连接?

python - 是否可以在没有迭代器变量的情况下实现 Python for range 循环?