3 回答

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
更新。如果您也想要計(jì)數(shù),我寧愿將大部分代碼重寫為:
d={('large','blue'):4,('cute','blue'):3,('large','blue','dog'):2,
('cute','blue','dog'):2,('cute','blue','elephant'):1}
completed = {}
for k,v in d.items():
if len([k1 for k1,v1 in d.items() if k != k1 and set(k).issubset(set(k1))]) != 1:
completed[k] = v
print(completed)
結(jié)果
{('cute', 'blue'): 3, ('large', 'blue', 'dog'): 2, ('cute', 'blue', 'dog'): 2, ('cute', '藍(lán)色', '大象'): 1}
我還沒有檢查性能。我就交給你了。
--
換個(gè)怎么樣
for f in final_list:
if not completed:
completed.add(f)
else:
if sum(f in s for s in completed)==1:
continue
和
for f in final_list:
if len([x for x in final_list if f != x and f in x]) != 1:
completed.add(f)
這是你想要的?

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊
這應(yīng)該有效:
previous = " "
previousCount = 0
for words in sorted([ " ".join(key) for key in d ]) + [" "]:
if words.startswith(previous):
previousCount += 1
else:
print(previous,previousCount)
if previousCount < 2 and previous != " ":
del d[tuple(previous.split(" "))]
previous = words
previousCount = 0

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個(gè)贊
必須有更有效的(非O(n^2))方法來做到這一點(diǎn),但這似乎是您想要的:
input = {
('large','blue'): 4,
('cute','blue'): 3,
('large','blue','dog'): 2,
('cute','blue','dog'): 2,
('cute','blue','elephant'): 1,
}
keys = set(' '.join(k) for k in input)
filtered = {
tuple(f.split())
for f in keys
if sum(f != k and f in k for k in keys) == 1
}
result = {k: v for k, v in input.items() if k not in filtered}
from pprint import pprint
pprint(sorted(result.items()))
結(jié)果:
[(('cute', 'blue'), 3),
(('cute', 'blue', 'dog'), 2),
(('cute', 'blue', 'elephant'), 1),
(('large', 'blue', 'dog'), 2)]
根據(jù)您的要求,這個(gè)想法是將出現(xiàn)一次的鍵識(shí)別為其他鍵的一部分。
添加回答
舉報(bào)