我有一个嵌套列表,如下所示:
test = [['hello', 'hola'], ['hello, 'bonjour', 'hola'], ['hello', 'ciao', 'namaste'], ['hola', 'ciao'], ['hola', 'ciao], ['namaste', 'bonjour', 'bonjour']]我感兴趣的是从每个子列表中删除所有元素,如果它不存在于至少X个子列表总数中(共享单词具有定义共享的阈值)。对于这个例子,如果我们设置X= 3,那么只有'hello‘、'hola’和'ciao‘的值将保留在任何列表中,从而产生:
shared = [['hello', 'hola'], ['hello, 'hola'], ['hello', 'ciao'], ['hola', 'ciao'], ['hola', 'ciao], []]我还想要另一个具有精确逆逻辑的列表,保留小于X子列表总数的值,从而从所有列表中删除“hello”、“hola”和“ciao”。
这是如何做到的呢?我会在这里放一些代码,但是作为初学者在Python中编写登录名却让我不知所措。
谢谢,杰克
编辑:注意,bonjour显示3次,但只出现在两个子列表中,因此它不被认为是共享的。
发布于 2018-06-14 19:00:46
首先,在扁平列表上使用collections.Counter查找每个单词的计数,使用一个集合忽略单个子列表中的重复值:
appearances = Counter(word for sub in arr for word in set(sub))
# Counter({'hola': 4, 'hello': 3, 'ciao': 3, 'bonjour': 2, 'namaste': 2})接下来,使用列表理解和字典查找( O(1)操作)只返回出现在足够子列表中的单词:
[[word for word in sub if appearances[word] >= threshold] for sub in arr]将所有这些放在一个简单的函数中,并返回您想要的结果:
from collections import Counter
def threshold_filter(arr, threshold):
appearances = Counter(word for sub in arr for word in set(sub))
return [
[word for word in sub if appearances[word] >= threshold]
for sub in arr
]
print(threshold_filter(test, 3))
# Result
[['hello', 'hola'], ['hello', 'hola'], ['hello', 'ciao'], ['hola', 'ciao'], ['hola', 'ciao'], []]https://stackoverflow.com/questions/50864138
复制相似问题