Python:从列表列表中删除列表?

时间:2016-02-05 16:23:35

标签: python performance list python-3.x

我有一套说法

char={'J','A'}

和列表

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

我正在尝试删除列表content中没有'J' & 'A'的列表项 我做的是

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)

有没有有效的写作方式?如果charcontent没有更多元素,则计算需要很长时间。

5 个答案:

答案 0 :(得分:3)

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

content中包含' J'的所有列表和' A':

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

content中包含' J'的所有列表或者' 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]]

答案 1 :(得分:2)

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]

答案 2 :(得分:2)

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

答案 3 :(得分:1)

我会像这样写

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)

答案 4 :(得分:1)

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]