从列表列表中删除列表Python

时间:2019-02-01 16:51:48

标签: python list numpy

我有一个列表列表:

[[0.0,3.3, 4.9, 7.5], [4, 6, 90, 21, 21.1], [3, 43, 99, 909, 2.11, 76, 76.9, 1000]]

如果该子列表包含给定范围之外的元素,我想从该列表中删除该子列表。

例如;范围= 3、15

因此,如果子列表包含-69,-17、0、1、2、15.1、246.99,即超出该范围的任何元素,我希望删除该子列表。

应返回的输出是列表列表,其中所有子列表仅包含该范围内的值:

[[6, 5, 7, 13, 12], [4, 6, 10], [9, 9, 4, 5, 11], [4, 4]]

我知道这里也有类似的问题,

Removing sublists from a list of lists

Python - Remove list(s) from list of lists (Similar functionality to .pop() )

我无法使用这些解决方案。

我的目标是不删除列表的重复项:对此有很多疑问,但这不是我的目标。

我的代码:

max_value = 15
min_value = 3

for sublist in my_list:
  for item in sublist:
    if(item < min_value):
        my_list.pop(sublist)
    if(item > max_value):
        my_list.pop(sublist)
print(my_list)

错误:

TypeError: 'list' object cannot be interpreted as an integer

3 个答案:

答案 0 :(得分:9)

您可以使用列表理解。这是示例输入和输出。这个想法很简单:对于每个子列表,只需检查minmax是否超出期望的限制。

list_1 = [[0.0,3.3, 4.9, 7.5], [4, 6, 9, 11, 12.1], [3, 43, 99, 909, 2.11, 76, 76.9, 1000], ]

left = 3
right = 15

list_2 = [i for i in list_1 if (min(i)>=left and max(i)<=right)]
print (list_2)
# [[4, 6, 9, 11, 12.1]]

答案 1 :(得分:4)

您错误来自使用.pop()的方法,其中期望的整数索引作为其参数,当你真的是.remove()。然而,即使这种修正后.remove()你可以从尝试在遍历它从列表中删除项目也遇到错误。清洁器的方法是一个列表理解:

my_list = [[0.0,3.3, 4.9, 7.5], [4, 6, 90, 21, 21.1], [3, 43, 99, 909, 2.11, 76, 76.9, 1000]]
min_value = 3
max_value = 100

my_list[:] = [sublist for sublist in my_list if all(min_value <= x <= max_value for x in sublist)]

答案 2 :(得分:1)

列表理解

new_list = [sublist for sublist in list if not any(el in range(a, b) for el in sublist)]