【问题标题】:List comprehension on nested lists with condition具有条件的嵌套列表上的列表理解
【发布时间】:2021-11-17 01:25:04
【问题描述】:

我有一个清单

list1 = [ [2,3,4] ,[5,6,7] ,[1,5,8] ,[2,3,{'key1':12}] ]

我需要从 list1 中删除包含字典元素的列表并生成 list2 应该是 [ [2,3,4] ,[5,6,7] ,[1,5,8] ]

使用 for 循环我可以得到 list2 之类的

for e1 in list1:
    condition = 0
    for e2 in e1:
        if type(e2) is dict:
            condition = 1
    if not condition:
        list2.append(e1)

如何通过列表理解获得 list2 的结果?

【问题讨论】:

    标签: python python-3.x list list-comprehension


    【解决方案1】:

    试试:

    list1 = [[2, 3, 4], [5, 6, 7], [1, 5, 8], [2, 3, {"key1": 12}]]
    
    list2 = [l for l in list1 if dict not in map(type, l)]
    print(list2)
    

    打印:

    [[2, 3, 4], [5, 6, 7], [1, 5, 8]]
    

    或者使用any()(感谢@chepner):

    list2 = [l for l in list1 if not any(isinstance(x, dict) for x in l)]
    print(list2)
    

    【讨论】:

    • ... if not any(instanceof(x, dict) for x in l) 会更惯用。
    • @chepner 感谢您的建议...我已添加。
    • 是的,它有效。感谢您的回复。
    猜你喜欢
    • 2019-06-07
    • 2022-11-07
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多