连接存储在一个对象中的多个列表

Concatenating mulitple lists stored in one object

我目前正在使用 PRAW 从 reddit 页面中提取评论。我想将评论正文中的某些词与 csv 文件中的值相匹配。以下是我目前正在使用的内容:

submission.comments.replace_more(limit=None)
for comment in submission.comments.list():
    results = (re.findall(r'[A-Z]{3,5}',comment.body))
    print(results)

输出:

[]
['HCMC']
[]
[]
['ASRT']
[]
[]
['CBBT', 'TLSS']
['LLEX']
[]

我知道 comment.body 实际上只是存储在一个对象中的一组列表。有没有一种方法可以将列表连接成一个列表?

您可以使用 itertools.chain.from_iterables:

>>> from itertools import chain
>>> list(chain.from_iterable(re.findall(r'[A-Z]{3,5}',comment.body)
                             for comment in submission.comments.list()))
['HCMC', 'ASRT', 'CBBT', 'TLSS', 'LLEX']

或者只是遍历 results 并将其项目重写到新列表中,如下所示:

concatenated = []
for lst in results:
  for item in lst:
    concatenated.append(item)

本文中的许多其他方式:https://www.pythonpool.com/flatten-list-python/