python - 在python中将多个列表合并为一个列表

标签 python

我有一个包含其他列表的列表:

list_of_lists = [[['2019-03-27-16:08:21 Now:(87.0866) Epoch:(1553728101) 45(secs)ago ItemID:(51141)', '2019-03-20-16:09:21 7d:(87.2040) Epoch:(1553123361) 604785(secs)ago ItemID:(51141)', 'Interval:(1m) Diff:(-0.1174) Now_[less-than]_Past(7d) GPM:(0.00008153) +GROWTH'], 'OK: Date:[2021-04-07 10:43:10.037075] Days.Until:[741.773648417]']]

如何将这些列表合并到一个列表中,使其看起来像这样:

['2019-03-27-16:08:21 Now:(87.0866) Epoch:(1553728101) 45(secs)ago ItemID:(51141)', '2019-03-20-16:09:21 7d:(87.2040) Epoch:(1553123361) 604785(secs)ago ItemID:(51141)', 'Interval:(1m) Diff:(-0.1174) Now_[less-than]_Past(7d) GPM:(0.00008153) +GROWTH', 'OK: Date:[2021-04-07 10:43:10.037075] Days.Until:[741.773648417]']

我在网上找到了一些代码,但它没有达到我想要的效果:

flattened_list = [y for x in list_of_lists for y in x]

我还更喜欢一个不需要 pip install 任何不属于默认 python 包的模块的解决方案。

最佳答案

使用简单的递归方法,您可以处理任何级别的嵌套:

def flat(l):
    if isinstance(l, list):
        result = []
        for i in l:
            result = result + flat(i)
        return result
    else:
        return [l]

>>> flat(list_of_lists)
['2019-03-27-16:08:21 Now:(87.0866) Epoch:(1553728101) 45(secs)ago ItemID:(51141)', '2019-03-20-16:09:21 7d:(87.2040) Epoch:(1553123361) 604785(secs)ago ItemID:(51141)', 'Interval:(1m) Diff:(-0.1174) Now_[less-than]_Past(7d) GPM:(0.00008153) +GROWTH', 'OK: Date:[2021-04-07 10:43:10.037075] Days.Until:[741.773648417]']

另一个例子:

>>> flat([1,2,[3,[4,5]],6,[7,8]])
[1, 2, 3, 4, 5, 6, 7, 8]

关于python - 在python中将多个列表合并为一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55387899/

相关文章:

python - 避免在自定义用户模型中为 django allauth 创建用户名字段

python - 如何在Node JS中访问当前文件文件夹之外的文件

python - CentOS Apache服务器无法正确部署Dash 1.4.0,网页一直处于上传状态,为什么?

python - 为什么[:1] and [0] do not generate the same result?

python - 属性错误: The vocab attribute was removed from KeyedVector in Gensim 4. 0.0

python - 附加到 DataFrame 会转换数据类型

python - 没有任何缓存的随机偏移二进制原始磁盘写入

python - 为什么人们会使用 globals() 来定义变量

python类相互依赖,如何初始化?

Python 循环导入