我有一个 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/