【问题标题】:Not able to print the desired output with these python lists无法使用这些 python 列表打印所需的输出
【发布时间】:2019-04-14 03:36:10
【问题描述】:

我希望我的源代码输出是这样的:

Lists: 1 3 4 2 1 2 1 3; 4 4 2 4 3 2 4 4 3 1 3    
[2, 3]

Lists : 1 1 2 3 4 5; 2 3 4 5 6    
[]

Lists : ;   
[]

Lists:

我想编写一个函数,它接受两个列表并返回在两个列表中多次出现的所有元素,但我最终会在这些列表中找到共同的元素。我的退货清单应按升序排列,不得重复。

def occur_multiple(a, b):
    a_set = set(a)
    b_set = set(b)
    # check length  
    if len(a_set.intersection(b_set)) > 0:
       return (a_set.intersection(b_set))
    else:
       return ("no common elements")

while True:
    original_string = input("Lists: ")
    if not original_string:
        exit()
    first_split = original_string.split(';')
    first_list, second_list = [elem.split(' ') for elem in first_split]
    first_list.sort()
    second_list.sort()
    print(occur_multiple(first_list, second_list))

【问题讨论】:

  • 添加有问题的预期结果。使用set() 删除“多次出现”,因此您找不到它们

标签: python


【解决方案1】:

列表的计数功能可能对您的任务有所帮助。我已经修改了您的代码,使其通过交集集中的元素并检查两个列表中的计数是否大于 1。

def occur_multiple(a, b):    
    a_set = set(a)    
    b_set = set(b)
    # check length
    ans_set = set()
    c = a_set.intersection(b_set)
    if len(c) > 0:
        for i in c:
            if a.count(i) > 1 and b.count(i) > 1:
                ans_set.add(i)
        return (sorted(list(ans_set)))
    else:
        return ("no common elements")

另外,您可能希望将列表输入更改为整数。为了改进,您可能希望将每个元素的计数存储在字典中,而不是多次读取列表。

【讨论】:

    【解决方案2】:

    使用 NumPy 函数 np.uniquenp.intersect1d

    import numpy as np
    
    def my_fun(a, b):
        val_1, count_1 = np.unique(a, return_counts=True)       # Find unique elements and 
        val_2, count_2 = np.unique(b, return_counts=True)       # number of occurrences
    
        val_1 = val_1[count_1 > 1]                              # Retain elements occurring
        val_2 = val_2[count_2 > 1]                              # more than once
    
        result = np.intersect1d(val_1, val_2)                   # Set intersection
        return list(result)                                     # Convert to list
    
    >>> a = [1, 3, 4, 2, 1, 2, 1, 3]
    >>> b = [4, 4, 2, 4, 3, 2, 4, 4, 3, 1, 3]
    >>> c = my_fun(a, b)
    >>> print(c)
    [2, 3]
    
    >>> a = [1, 1, 2, 3, 4, 5]
    >>> b = [2, 3, 4, 5, 6]
    >>> c = my_fun(a, b)
    >>> print(c)
    []
    
    >>> a = [-5, 1, 2, 3, 4, 1, 0, 1, 2, 4, 4, 2, -5]
    >>> b = [1, 3, 4, 5, -5, -5, -5, 1, 4]
    >>> c = my_fun(a, b)
    >>> print(c)
    [-5, 1, 4]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多