在列表中保留确切的单词,并删除其他单词

时间:2019-03-14 22:57:43

标签: python python-3.x list

在这里,我有一个列表a,还有另一个列表b,其中包含一些字符串。对于列表a中的字符串,我想保留出现在列表b中的字符串。并删除列表b中未出现的其他字符串。

例如:

list_a = [['a','a','a','b','b','b','g','b','b','b'],['c','we','c','c','c','c','c','a','b','a','b','a','b','a','b']]
list_b = ['a']

我期望的结果是:

像这样获取list_a:[['a','a','a'],['a','a','a','a']]

但是,当我运行我的代码时:

data = [['a','a','a','b','g','b'],['we','c','a','b','a','a','b','a','b']]
keep_words = ['a']
for document in data:
    print('######')
    for word in document:
        print(word)
        if word in keep_words:
            document.remove(word)
            print(document)
print('#####')
print(data)

我得到这个结果:

line 1:######
line 2:a
line 3:['a', 'a', 'b', 'g', 'b']
line 4:a
line 5:['a', 'b', 'g', 'b']
line 6:g
line 7:b
line 8:######
line 9:we
line 10:c
line 11:a
line 12:['we', 'c', 'b', 'a', 'a', 'b', 'a', 'b']
line 13:a
line 14:['we', 'c', 'b', 'a', 'b', 'a', 'b']
line 15:b
line 16:a
line 17:['we', 'c', 'b', 'b', 'a', 'b']
line 18:#####
line 19:[['a', 'b', 'g', 'b'], ['we', 'c', 'b', 'b', 'a', 'b']]

所以我很困惑: 为什么在第6行中,它打印单词“ g”而不是单词“ a”?因为在第5行中我们获得了一个列表['a','b','g','b'],所以在下一个for循环中,它应该在该列表的开头得到单词'a'。 / p>

任何人都可以告诉我为什么会发生这种情况以及如何解决我的问题?非常感谢你!

* Attached picture is my code and my result

2 个答案:

答案 0 :(得分:2)

永远不要在遍历数组时从数组中删除元素,这是解决您的问题的方法,该问题涉及用所需结果替换子列表(过滤):

data = [['a','a','a','b','g','b'],['we','c','a','b','a','a','b','a','b']]
keep_words = ['a']

for i in range(len(data)):
  data[i] = [d for d in data[i] if d in keep_words] # only keep desired data

print(data) # ==> [['a', 'a', 'a'], ['a', 'a', 'a', 'a']]

答案 1 :(得分:2)

如注释中所述,如果在迭代过程中对list进行突变时,您会遇到这种类型的side effects

另一种解决方案是利用Python的超快速且可读的list理解力

In [33]: [[a for a in l if a in list_b] for l in list_a]
Out[33]: [['a', 'a', 'a'], ['a', 'a', 'a', 'a']]

请注意,随着list_b的增长,您可能需要考虑使用set,在检查成员资格方面比list快很多 。它还将忽略任何重复的条目

In [52]: import random

In [73]: import string

In [74]: keep_s = set(['a', 'b', 'e'])

In [75]: keep_l = ['a', 'b', 'e']

# Create a random document -- random choice of 'a'-'f' between 1-100 times
In [78]: def rand_doc():
    ...:     return [random.choice(string.ascii_lowercase[:6]) for _ in range(random.randint(1,100))]
    ...:

# Create 1000 random documents
In [79]: docs = [rand_doc() for _ in range(1000)]

In [80]: %timeit [[word for word in doc if word in keep_l] for doc in docs]
4.39 ms ± 135 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [81]: %timeit [[word for word in doc if word in keep_s] for doc in docs]
3.16 ms ± 130 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
相关问题