[英]Find if a word is in list OR an element in the list is a subset of this word
[英]Python removing word if subset of other word in list
一個簡單的謎題,但我無法理解它:
用詞:我有一個單詞列表。 如果在我的列表中,該詞是列表中另一個值的“子集”,則刪除。
Input: ['car', 'car-10', 'truck-20']
Output: ['car-10', 'truck-20']
我們刪除了“car”,因為它是“car-10”的子集。 'car-10' 不是 'car' 的子集
Input: ['car', 'car-10', 'car-100']
Output: ['car-100']
我們刪除了“car”和“car-10”,因為它們是“car-100”的子集。
我真正想解決的問題,不要使用數字:
Input: ['car-strong', 'car', 'truck-weak']
Output: ['car-strong', 'truck-weak']
我們可能有“卡車”、“香蕉”、“蘋果”,而事物將是“apple-10”。
請注意,“類型”(汽車、卡車、蘋果等)始終是單詞的開頭。
要解析的典型列表長度約為 5-10 個元素。 (我猜是蠻力嗎?)
但是有大約 200,000 個這些短名單需要“清理”……這也是問題所在。
蠻力
l =['car', 'car-10', 'truck-20']
remove_me = [x for x in l
if any([y.startswith(x) for y in l if x!=y])]
result = [x for x in l if x not in remove_me]
為了獲得更好的性能,按字母順序排列列表以更快地找到候選“超集”,例如沿着
這是一個適用於所有類型輸入格式的解決方案:
input = ['car-strong', 'car', 'truck-weak']
delete = []
for idx,str in enumerate(input):
for idx2,str2 in enumerate(input):
if str in str2 and idx != idx2:
delete.append(str)
for str in delete:
input.remove(str)
print(input)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.