[英]Compare list of tuples, confirm subset based on condition?
給定一個單詞和一個單詞列表,我必須找到可以使用給定單詞的字母(字母數量)構建的列表元素/單詞。 我嘗試使用集合中的Counter
對象和python 2.7的cmp()
函數的定義(我正在使用3.6.5)。
從那以后,我開始意識到這種方法似乎對這樣的問題是不好的做法(以前,我試圖使用反對象字典進行比較)。 我的程序不起作用的原因是因為compare_fn依賴於列表之間的'>','<'操作,這些操作根據字典順序給出結果( 從此處引用 )。 因此,即使可以從“ ravenous”中創建“ raven”,但由於有序列表中char的順序,下面的程序也會失敗。
from collections import Counter
word = 'ravenous'
candidates = ["raven", "mealwheel", "rasputin"]
def count_fn(mystr):
return sorted(list(Counter(mystr).items()))
def compare_fn (c1,c2):
return ((c1>c2) - (c1<c2))
list_word = count_fn(word)
list_candidates = list(map(count_fn,candidates))
cmp_list = [compare_fn(list_word,i) for i in list_candidates]
cmp_list
#[-1, -1, -1] #should be [1,-1,-1]
因此,對於下面的兩個列表,如何確認list_candidates[0]
是list_word
的子集。 請注意,所述比較('a',1)
在list_word
針對('a',1)
在list_candidates[i]
也可('a',5)
在list_word
針對('a',1)
在list_candidates[i]
; 兩種情況都是正確的。
print(list_word)
#[('a', 1), ('e', 1), ('n', 1), ('o', 1), ('r', 1), ('s', 1), ('u', 1), ('v', 1)]
print(list_candidates[0])
#[('a', 1), ('e', 1), ('n', 1), ('r', 1), ('v', 1)]
我認為使用計數器是一個不錯的選擇。 不要把它們變成列表。 我特意返回了[True,False,False]而不是[1,-1,-1],但是您可以輕松地進行更改。
而且:我使用列表理解而不是map,因為它在python中是最新的,但是語義是相同的。
from collections import Counter
word = 'ravenous'
candidates = ["raven", "mealwheel", "rasputin"]
def count_fn(mystr):
return Counter(mystr)
def compare_fn (c1,c2):
return all(c1[char] >= count for char, count in c2.items())
counter_word = count_fn(word)
list_candidates = [count_fn(candidate) for candidate in candidates]
cmp_list = [compare_fn(counter_word, i) for i in list_candidates]
print(cmp_list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.