简体   繁体   English

在列表中查找元素,以使元素不应具有相似的数字

[英]Finding the elements in list such that elements should not have similar numbers

Consider a list = [23,52,44,32,78] 23,52,32 all these elements have at least one digit common so the set i want to filter is [44,78] as they don't have any common numbers. 考虑一个list = [23,52,44,32,78] 23,52,32所有这些元素都至少有一个公共位数,因此我要过滤的集合为[44,78]因为它们没有任何共同之处数字。

Another example: [52,12,255,211,223,123,64,87,999] would be filtered as [64,87,999] 另一个示例: [52,12,255,211,223,123,64,87,999]将被过滤为[64,87,999]

My current idea is to convert all the numbers into list like [2,3],[5,2]... and take a intersection of those but i couldn't understand how to compare all these sub-lists and filter out the desired numbers. 我目前的想法是将所有数字转换成[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

handle the numbers as a list of characters and use set conversion and test if disjoint. 将数字作为字符列表进行处理,并使用set转换并测试是否相交。 Maybe not the most performant one-liner but works: 也许不是性能最高的一线飞机,但可以工作:

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)]

result: 结果:

>>> unique
[44, 78]

maybe slightly faster: convert to string once, process strings, convert back to integers in the end: 也许稍微快一点:一次转换为字符串,处理字符串,最后转换回整数:

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)]

You can use Counter to find non-common digits: 您可以使用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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM