获取列表的内容并将其附加到另一个列表 [英] Take the content of a list and append it to another list

查看:64
本文介绍了获取列表的内容并将其附加到另一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 will get specific lines out of a file and will save them in a list.

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

Then a second list is used to save these lines, and start a new cycle over another file.

我的想法是在for循环完成后获取列表,将其转储到第二个列表中,然后开始一个新的循环,将第一个列表的内容再次转储到第二个列表中,但将其追加,因此第二个列表将是在我的循环中创建的所有较小列表文件的总和.仅在满足某些条件的情况下,才必须附加该列表.

My idea was to get the list once that the for cycle is done, dump it into the second list, then start a new cycle, dump the content of the first list again into the second but appending it, so the second list will be the sum of all the smaller list files created in my loop. The list has to be appended only if certain conditions met.

类似于以下内容:

# 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

这有意义还是我应该选择其他路线?

Does this makes sense or should I go for a different route?

我需要一种效率高,不会占用太多周期的东西,因为日志列表很长,每个文本文件都很大.所以我认为这些清单符合目的.

I need something efficient that would not take up too many cycles, since the list of logs is long and each text file is pretty big; so I thought that the lists would fit the purpose.

推荐答案

您可能想要

list2.extend(list1)

代替

list2.append(list1)

区别在于:

>>> 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]

由于list.extend()接受任意迭代,因此您也可以替换

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

for line in mylog:
    list1.append(line)

作者

list1.extend(mylog)

这篇关于获取列表的内容并将其附加到另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆