我试图了解获取列表的内容并将其附加到另一个列表是否有意义。
我通过循环函数创建了第一个列表,它将从文件中获取特定行并将它们保存在列表中。
然后使用第二个列表来保存这些行,并在另一个文件上开始一个新的循环。
我的想法是在 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/