考虑一个list = [23,52,44,32,78]
23,52,32
,所有这些元素至少有一个公共数字,所以我要过滤的集合为[44,78]
,因为它们没有任何公共数字。
另一个示例:[52,12,255,211,223,123,64,87,999]
将被过滤为[64,87,999]
我目前的想法是将所有数字都转换成[2,3],[5,2] ...之类的列表,并取它们的交集,但是我不明白如何比较所有这些子列表,并且过滤出所需的数字。
def convert_into_sublist(i):
sublist = [int(x) for x in str(i)]
def intersection(l1, l2):
l3 = [value for value in l1 if value in l2]
if(len(l3)==0):
return 1
答案 0 :(得分:2)
将数字作为字符列表处理,并使用set
转换并测试是否相交。也许不是性能最高的一线飞机,但可以工作:
lst = [23,52,44,32,78]
# optional: remove duplicates:
lst = set(lst)
unique = [l for l in lst if all(set(str(x)).isdisjoint(str(l)) for x in lst if x != l)]
结果:
>>> unique
[44, 78]
可能会稍快一些:一次转换为字符串,处理字符串,最后转换回整数:
lst = [str(x) for x in lst]
unique = [int(l) for l in lst if all(set(x).isdisjoint(l) for x in lst if x != l)]
答案 1 :(得分:0)
您可以使用Counter
查找非公共数字:
from collections import Counter
from itertools import chain
from operator import itemgetter
lst = [23, 52, 44, 32, 78]
sets = [set(str(i)) for i in lst]
# [{'3', '2'}, {'5', '2'}, {'4'}, {'3', '2'}, {'7', '8'}]
c = Counter(chain.from_iterable(sets))
# Counter({'2': 3, '3': 2, '5': 1, '4': 1, '7': 1, '8': 1})
new_lst = []
for num, set_ in zip(lst, sets):
counts = itemgetter(*set_)(c)
if counts == 1 or set(counts) == {1}:
new_lst.append(num)
print(new_lst)
# [44, 78]