无法使用这些python列表打印所需的输出

时间:2019-04-14 03:36:11

标签: python

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

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

2 个答案:

答案 0 :(得分:0)

列表的计数功能可能对您的任务很有帮助。我已经修改了您的代码,以使其通过交集中的元素,并检查两个列表中的计数是否都大于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")

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

答案 1 :(得分:0)

使用NumPy函数lnp.unique

np.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)
[]