python - 带条件的嵌套列表的列表理解

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

我有一个 list

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 的结果?

最佳答案

尝试:

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)

关于python - 带条件的嵌套列表的列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69303509/

相关文章:

python - 如何扫描最新的 TRX 区 block 以获取转账事件以检查地址是否有新交易

python - 如何创建包含 27.000 条线的抖动图?

python - 基于辅助系列从 pandas DataFrame 中进行选择

r - 在 R 中的数据框列表中更改列名称的子集

python - 从函数列表中获取随机函数并调用所选函数

python - 在 python 中处理大量数据,我应该使用多线程/进程吗?

java - RPC 框架可用吗?

python - 如何在 Airflow 中有多个分支?

python - 接收 key 错误 : "None of [Int64Index([ ... dtype=' int6 4', length=1323)] are in the [columns]"

java - 如何只从列表中删除一个重复项?