【问题标题】:How do you compare three lists and add the duplicates to one list and the non-duplicates to another list?您如何比较三个列表并将重复项添加到一个列表而将非重复项添加到另一个列表?
【发布时间】:2020-04-16 01:55:27
【问题描述】:

我需要设计一种方法来比较三个列表中的所有数字,并且如果所有三个列表中都存在一个数字 - 我必须将它添加到 matching_numbers 列表中。如果一个数字与其他任何数字都不匹配,那么我必须将它添加到 unique_numbers 列表中。我尝试使用 for 循环,但我只能完成等式的一半,而且我不确定如何将所有不匹配的数字添加到 unique_numbers 列表中。我也不希望我的 matching_numbers 或 unique_numbers 列表中有任何重复项。

list_1 = []

list_2 = []

list_3 = []

matching_numbers = []

unique_numbers = []

countone = 0

counttwo = 0

countthree = 0

import random

name = input("Hello USER. What will your name be?")

print("Hello " + name + ". Welcome to the NUMBERS program.")

amountone = int(input("How many numbers do you wish to have for your first list? Please choose from between 1 and 15."))

while countone != amountone:
  x = random.randint(1, 50)
  list_1 += [x,]
  print(list_1)
  countone += 1

amounttwo = int(input("For your second list, how many numbers do you wish to have? Please choose from between 1 and 15."))

while counttwo != amounttwo:
  x = random.randint(1, 50)
  list_2 += [x,]
  print(list_2)
  counttwo += 1

amountthree = int(input("For your third list, how many numbers do you wish to have? Please choose from between 1 and 15."))

while countthree != amountthree:
  x = random.randint(1, 50)
  list_3 += [x,]
  print(list_3)
  countthree += 1

for a in list_1:
    for b in list_2:
        for c in list_3:
          if a == b and b == c:
            matching_numbers = list(set(list_1) & set(list_2) & set(list_3))
          else:
            unique_numbers = 

【问题讨论】:

    标签: python python-3.x list concatenation


    【解决方案1】:

    这是Sets 最适合的类型。与列表不同,检查是否存在的复杂性为O(n),集合查找为O(1)。此外,集合已经具有检查交叉点、差异等的方法。因此,三个集合中的项目可以计算为三个集合的交叉点:

    all_numbers = set_1 | set_2 | set_3
    matching_numbers = set_1 & set_2 & set_3
    unique_numbers = all_numbers - matching_numbers
    

    【讨论】:

    • 这不会在三组中找到唯一的数字。考虑三个 set_1:{7}、set_2:{9}、set_3:{7}。 matching_numbers 将为空,unique_numbers 将为 {7, 9},这是不正确的,因为 7 分为两组。
    • OP 的要求没有说明应如何处理重复;我认为 set 实现更正确,但谁知道要求的是什么。
    • 我猜我读到了If a number doesn’t match any of the other numbers, then I have to add it to the unique_numbers list.,这意味着unique_numbers 中的数字将是全球唯一的。
    猜你喜欢
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 2022-08-02
    相关资源
    最近更新 更多