Perhaps a bit more semantic would be to use any.
for sublist in the_list:
if any(item in filters_exclude for item in sublist):
continue
filtered_list.append(sublist)
Maybe overkill, but you could even factor that into its own function then use the builtin filter
def good_list(some_list):
return not any(item in filters_exclude for item in some_list)
filtered_list = filter(good_list, the_list)
This should accomplish the goal you described. However, the code you wrote has potential issues, as mentioend in the comments.
Answer from sytech on Stack OverflowPerhaps a bit more semantic would be to use any.
for sublist in the_list:
if any(item in filters_exclude for item in sublist):
continue
filtered_list.append(sublist)
Maybe overkill, but you could even factor that into its own function then use the builtin filter
def good_list(some_list):
return not any(item in filters_exclude for item in some_list)
filtered_list = filter(good_list, the_list)
This should accomplish the goal you described. However, the code you wrote has potential issues, as mentioend in the comments.
You can use list comprehension:
the_list = [['blue'], ['blue', 'red', 'black'], ['green', 'yellow'],['orange'], ['white', 'gray']]
filters = ['blue', 'white']
final_l = [i for i in the_list if not any(b in filters for b in i)]
Output:
[['green', 'yellow'], ['orange']]
Or, using filter:
final_l = filter(lambda x:not any(b in filters for b in x), the_list)
Deep Filter a List of Lists
how to filter nested list in python - Stack Overflow
nested list filtering in python? - Stack Overflow
pandas - Filtering a nested list in python - Stack Overflow
Try this list comprehesion.
>>> a = [[(1,2),(7,-5),(7,4)], [(5,6),(7,2)], [(8,2),(20,7),(1,4)]]
>>> [l for l in a if all((0<x<10 and 0<y<10) for x,y in l)]
[[(5, 6), (7, 2)]]
The following snippet will print [[(5, 6), (7, 2)]]:
a=[[(1,2),(7,-5),(7,4)],[(5,6),(7,2)],[(8,2),(20,7),(1,4)]]
def f(sub):
return all(map(lambda (x,y): (0 < x < 10 and 0 < y < 10), sub))
a = filter(f, a)
print a
If you don't want to preserve the inner lists you can do it with a double list comprehension:
[item for inner in my_list for item in inner if 'yellow' in item]
yields:
[' Example4 (yellow)', ' Example14 (yellow)']
If you want to preserve the inner lists you can do it like this:
[ [item for item in inner if 'yellow' in item] for inner in my_list ]
yields:
[[' Example4 (yellow)'], [' Example14 (yellow)']]
Import necessary packages and intialize data:
import pandas as pd
import re
my_list = [['Example1 (purple)',
' Example2 (blue)',
' Example3 (orange)',
' Example4 (yellow)',
' Example5 (red)',
' Example6 (pink)',
' Example7 (sky)'],
['Example8 (purple)',
' Example9 (blue)',
' Example10 (orange)',
' Example11 (sky)',
' Example12 (green)',
' Example13 (green)',
' Example14 (yellow)',
' Example15 (red)',
' Example16 (pink)',
' Example17 (pink)',
' Example18 (green)',
' Example19 (sky)']]
Flatten the list, so its not nested lists in lists. (This is why you got an error that lists don't have split. If you do [x.split() for x in my_list] it will give an error because the elements made up of my_list are lists)
Define a flatlist function and flatten list:
flat_list = lambda l: [item for sublist in l for item in sublist]
flat = flat_list(my_list)
Create an empty dataframe
df = pd.DataFrame({})
Extract out the elements of the single flat list. this strips it of whitespace, then splits it by the space, taking the 0th element for the "Example1", and then strips it again to remove whitespace. do it again but take the 1st element for the color. Wrap it in () and separate by a comma to return it as a tuple.
splitout = [(x.strip().split(' ')[0].strip(), x.strip().split(' ')[1]) for x in pd.Series(flat)]
set the two dataframe columns. the first is just grabbing the first element of the splitout which is always Example, the second uses re.sub to remove the () from the color
df['Example'] = [x[0] for x in splitout]
df['Color'] = [re.sub('[/(/)]', '', x[1]) for x in splitout]
Example Color
0 Example1 purple
1 Example2 blue
2 Example3 orange
3 Example4 yellow
4 Example5 red
5 Example6 pink
6 Example7 sky
7 Example8 purple
8 Example9 blue
9 Example10 orange
10 Example11 sky
11 Example12 green
12 Example13 green
13 Example14 yellow
14 Example15 red
15 Example16 pink
16 Example17 pink
17 Example18 green
18 Example19 sky
Then you can pivot into a larger dataframe with colors for columns:
pd.pivot_table(df.assign(v=1), index='Example', columns='Color', values='v')
Color blue green orange pink purple red sky yellow
Example
Example1 NaN NaN NaN NaN 1.0 NaN NaN NaN
Example10 NaN NaN 1.0 NaN NaN NaN NaN NaN
Example11 NaN NaN NaN NaN NaN NaN 1.0 NaN
Example12 NaN 1.0 NaN NaN NaN NaN NaN NaN
Example13 NaN 1.0 NaN NaN NaN NaN NaN NaN
Example14 NaN NaN NaN NaN NaN NaN NaN 1.0
Example15 NaN NaN NaN NaN NaN 1.0 NaN NaN
Example16 NaN NaN NaN 1.0 NaN NaN NaN NaN
Example17 NaN NaN NaN 1.0 NaN NaN NaN NaN
Example18 NaN 1.0 NaN NaN NaN NaN NaN NaN
Example19 NaN NaN NaN NaN NaN NaN 1.0 NaN
Example2 1.0 NaN NaN NaN NaN NaN NaN NaN
Example3 NaN NaN 1.0 NaN NaN NaN NaN NaN
Example4 NaN NaN NaN NaN NaN NaN NaN 1.0
Example5 NaN NaN NaN NaN NaN 1.0 NaN NaN
Example6 NaN NaN NaN 1.0 NaN NaN NaN NaN
Example7 NaN NaN NaN NaN NaN NaN 1.0 NaN
Example8 NaN NaN NaN NaN 1.0 NaN NaN NaN
Example9 1.0 NaN NaN NaN NaN NaN NaN NaN
whole code:
import pandas as pd
import re
flat_list = lambda l: [item for sublist in l for item in sublist]
flat = flat_list(my_list)
splitout = [(x.strip().split(' ')[0].strip(), x.strip().split(' ')[1]) for x in pd.Series(flat)]
df = pd.DataFrame({})
df['Example'] = [x[0] for x in splitout]
df['Color'] = [re.sub('[/(/)]', '', x[1]) for x in splitout]
pivot = pd.pivot_table(df.assign(v=1), index='Example', columns='Color', values='v')
Simple list comprehension:
L = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
newList = [l[0:2] for l in L if l[2] == 'G']
print(newList)
The output:
[['4.2', '3.4'], ['8.7', '5.4']]
I would suggest using a collections.defaultdict, as a multi-value dictionary:
from collections import defaultdict
d = defaultdict(list)
for x in L:
d[x[2]].append(x[:2])
Now you can use d['G'] to get what you wanted, but also d['H'] to get the result for 'H'!
Edit: Source append multiple values for one key in Python dictionary
First of all, there is nothing wrong with defining a filtering or mapping function as a regular function via def if it would be a benefit to readability - remember "Readability counts" and "Sparse is better than dense". Just because there are inline lambda function in the language, does not mean you have to squeeze your logic into it.
Since you eventually want to build a generic solution for an arbitrary list depth, you can recursively apply the filtering function via map() + filter() to remove the None values:
def filter_function(e):
if isinstance(e, list):
return filter(None, map(filter_function, e))
elif e > 10:
return e
my_list = list(filter_function(my_list))
Note that list() would be needed on Python 3.x, since filter() does not return a list.
Demo:
>>> my_list = [[1], [2, [3, 12, [4, 11, 12]]], [5, 6, 13, 14], [15]]
>>>
>>> def filter_function(e):
... if isinstance(e, list):
... return filter(None, map(filter_function, e))
... elif e > 10:
... return e
...
>>>
>>> print(list(filter_function(my_list)))
[[[12, [11, 12]]], [13, 14], [15]]
Well, this is not a best practice, but you can create a lambda function: use parenthesis to group conditions:
f = lambda e: filter(None, [f(y) for y in e]) if isinstance(e, list) else (e if e > 10 else None)
my_list = [[1], [2, [3, 12, [4, 11, 12]]], [5, 6, 13, 14], [15]]
>>> f(my_list)
[[[12, [11, 12]]], [13, 14], [15]]
For python 3 users:
f = lambda e: list(filter(None, [f(y) for y in e])) if isinstance(e, list) else (e if e > 10 else None)
I think you can just index it out:
np.array(the_nested)[:,1:]
In your case:
the_nested = [[51502, 2, 0, 0, 1, 1],
[8046 ,2 ,0 , 1 ,1 ,2],
[40701, 1 ,1 ,1 ,1 ,1]]
>>> np.array(the_nested)[:,1:]
array([[2, 0, 0, 1, 1],
[2, 0, 1, 1, 2],
[1, 1, 1, 1, 1]])
Alternatively, with np.delete (no loop needed):
>>> np.delete(np.array(the_nested),0,axis=1)
array([[2, 0, 0, 1, 1],
[2, 0, 1, 1, 2],
[1, 1, 1, 1, 1]])
I see you have a list and if you don't want to use additional packages like numpy you can do something like this. But it involve looping. Also, it is not modifying the original list.
the_nested = [[51502, 2, 0, 0, 1, 1],
[8046 ,2 ,0 , 1 ,1 ,2],
[40701, 1 ,1 ,1 ,1 ,1]]
res = []
_ = [res.append(x[1:]) for x in the_nested]
# Output :
[[2, 0, 0, 1, 1], [2, 0, 1, 1, 2], [1, 1, 1, 1, 1]]