【问题标题】:Finding the elements in list such that elements should not have similar numbers查找列表中的元素,使得元素不应具有相似的数字
【发布时间】:2019-05-26 17:50:59
【问题描述】:

考虑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

【问题讨论】:

  • 你如何定义common digits,他们需要定义为common的最少出现次数是多少?在此基础上,可以想出一个逻辑
  • @DeveshKumarSingh 即使一个数字很常见,那么过滤列表中的所有数字都应该是不常见的。

标签: python python-3.x logic


【解决方案1】:

将数字处理为字符列表并使用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)]

【讨论】:

  • 这是一个不错的解决方案。由于x != l 测试,一个小问题似乎是重复数字的边缘情况。 [23,52,44,32,78, 44] 导致 [44, 78, 44] 不确定这是否是 OP 的问题。
  • 是的,在这种情况下,只需将输入设为set 即可消除欺骗。已编辑
【解决方案2】:

您可以使用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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2020-05-29
    • 2019-02-15
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多