Datalearner
Datalearner

Reputation: 185

filter a array in a list that contain a certain value

I have list

combi_col = [[0,1,2][0,1],[0],[1,2],[0,2],[1,2,3],[2,3],[3,1]

I want to filter this list to only show a list that only contain 0 in the array

The result should only keep all arrays in the list which contain 0

In addition, the array should not contain only 1 value. It should contain minimum 2 values

The result should look like

result = [[0,1,2][0,1],[0,2]]

Upvotes: 1

Views: 455

Answers (5)

khushi kumari
khushi kumari

Reputation: 1

list = [[0,1,2],[0,1],[0],[1,2],[0,2],[1,2,3],[2,3],[3,1]] result = []

for i in list: if 0 in i and len(i) >= 2: result.append(i)

Upvotes: 0

NiiRexo
NiiRexo

Reputation: 146

You can try something like this:

combi_col = [[0,1,2],[0,1],[0],[1,2],[0,2],[1,2,3],[2,3],[3,1]]
result = []

for entry in combi_col:
    if 0 in entry and len(entry) >= 2:
        result.append(entry)

Upvotes: 2

stukituk
stukituk

Reputation: 188

Answer from NiiRexo is correct, but you can do the same in one line using list comprehension:

result = [nested_list for nested_list in combi_col if len(nested_list)>1 and (0 in nested_list)]

Upvotes: 0

nadjagv
nadjagv

Reputation: 86

You could use built in filter:

filtered = list(filter(lambda list_element: 0 in list_element and len(list_element)>1, combi_col))

First parameter is function with which you filter, and second is collection to be filtered.

Upvotes: 0

Talha Tayyab
Talha Tayyab

Reputation: 27940

You can do in one line via list comprehension:

[x for x in combi_col if 0 in x and len(x) >= 2]
#[[0, 1, 2], [0, 1], [0, 2]]

Upvotes: 4

Related Questions