Rangooski
Rangooski

Reputation: 873

Python : Removing a List from List of List?

I have a set say

char={'J','A'}

and a list of list

content = [[1,'J', 2], [2, 'K', 3], [2, 'A', 3], [3,'A', 9], [5, 'J', 9]]

I am trying to remove the list items in list content, which don't have 'J' & 'A' What I did is

li = list(char)
char1= np.array(li)
content=np.array(content)
new_content=[]
for alphabet in content:
    if alphabet[1] in char1:
        new_content.append(alphabet)
print(new_content)

Is there any efficient way of writing? If char and content has more no of elements, then the computation takes long time.

Upvotes: 3

Views: 132

Answers (5)

timgeb
timgeb

Reputation: 78690

>>> content = [[1,'J', 2], [2, 'K', 3], [2, 'A', 3], [3,'A', 9], [5, 'J', 9]]
>>> char={'J','A'}

All lists in content which have 'J' AND 'A':

>>> [x for x in content if all(c in x for c in char)]
[]

All lists in content which have 'J' OR 'A':

>>> [x for x in content if any(c in x for c in char)]
[[1, 'J', 2], [2, 'A', 3], [3, 'A', 9], [5, 'J', 9]]

Upvotes: 3

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

content = [[1,'J', 2], [2, 'K', 3], [2, 'A', 3], [3,'A', 9], [5, 'J', 9]]
whitelist = {'J','A'}

content = [sub for sub in content if sub[1] not in whitelist]

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 113955

content = [[1,'J', 2], [2, 'K', 3], [2, 'A', 3], [3,'A', 9], [5, 'J', 9]]
whitelist = {'J','A'}

remove = set()
for i,sub in enumerate(content):
    if sub[1] not in whitelist: remove.add(i)

content = [sub for i,sub in enumerate(content) if i not in whitelist]

Upvotes: 2

jay s
jay s

Reputation: 531

I would write it like this

char={'J','A'}
content = [[1,'J', 2], [2, 'K', 3], [2, 'A', 3], [3,'A', 9], [5, 'J', 9]]

filter(lambda x: all([i in char for i in x]), content)

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 113955

content = [[1,'J', 2], [2, 'K', 3], [2, 'A', 3], [3,'A', 9], [5, 'J', 9]]
whitelist = {'J','A'}

i = 0
while i<len(content):
    if content[i][1] not in whitelist:
        blacklist.pop(i)
        continue
    i += 1

Upvotes: 2

Related Questions