【问题标题】:Getting rid of duplicates from a pair of corresponding lists从一对对应列表中删除重复项
【发布时间】:2020-11-19 06:47:59
【问题描述】:

这是我最近制作的一个程序。这段代码的目标是一对对应的列表。所以randomStringpt1[0] 对应于randomStringpt2[0]。我想将randomStringpt1[0]randomString2[0] 与用户在随机字符串中提供的其余对进行比较。但是在使用这段代码之后,看起来我已经多次复制了每一对,这与我所寻找的相反。我正在考虑使用字典,但后来意识到字典键只能有一个值,如果用户两次使用数字,这对我的情况没有帮助。有谁知道我可以如何减少重复? (我一直在运行的测试编号为randomStringpt1 = [1,3,1,1,3]randomStringpy2 = [2,4,2,3,4] )

randomStringpt1 = [1, 2, 3, 4, 5] #Pair of strings that correspond to each other("1,2,3,4,5" doesn't actually matter)
randomStringpt2 = [1, 2, 3, 4, 5]

for i in range(len(randomStringpt1)):
    randomStringpt1[i] = input("Values for the first string: ")
    randomStringpt2[i] = input("Corresponding value for the second string: ")
print(randomStringpt1) #numbers that the user chose for the first number of the pair
print(randomStringpt2) #numbers that the user chose for the second number of the pair
newStart = []
newEnd = []
for num1 in range(len(randomStringpt1)):
    for num2 in range(len(randomStringpt1)):
        if (int(randomStringpt1[num1]) != int(randomStringpt1[num2]) and int(randomStringpt2[num1]) != int(randomStringpt2[num2])):
            newStart.append(randomStringpt1[num1]) # Adding the pairs that aren't equal to each other to a new list
            newEnd.append(randomStringpt2[num1])
            newStart.append(randomStringpt1[num2])
            newEnd.append(randomStringpt2[num2])
        # else: 
        #   print("The set of numbers from the randomStrings of num1 are not equal to the ones in num2")

print(newStart)
print(newEnd)

【问题讨论】:

    标签: python-3.x list duplicates


    【解决方案1】:

    首先让我们分析一下代码中的 2 个错误, 每次一对与不同的比较时,循环内的 if 条件为真。这意味着对于您的示例,它应该输出 [1, 1, 3, 3, 3, 1, 1, 1, 1, 3, 3, 3] [2, 2, 4, 4, 4, 2, 2, 3, 3, 4, 4, 4] 因为您将每一对与存在的任何其他对进行比较。但是你的输出是不同的,因为你每次都附加两个对并且得到一个非常大的结果,所以你不应该附加 num2 对。

    现在,根据你所描述的你想要的,你应该循环每一对并检查它是否已经存在于输出列表中。所以for循环部分可以这样变化

    filtered = []
    for pair in zip(randomStringpt1,randomStringpt2):
        if pair not in filtered:
            filtered.append(pair) # Adding the pairs that aren't equal to each other to a new list
    

    zip 函数获取 2 个列表,并且对于每个循环,它从每个列表返回 2 个值,第一个值对,然后是第二个值,然后继续。过滤后的列表将采用以下格式[(1, 2), (3, 4), (1, 3)]

    或者,它可以像这样作为一个衬里:

    filtered = list(dict.fromkeys(zip(randomStringpt1, randomStringpt2)))
    

    使用字典识别唯一元素,然后将其转回列表 毕竟,您可以通过像这样拆分它们来获得代码中列表的原始格式

    newStart = [pair[0] for pair in filtered]
    newEnd = [pair[1] for pair in filtered]
    

    最后我应该告诉你多读一点关于 python 和它的 for 循环,因为 range(len(yourlist)) 不是 python 预期的遍历列表的方式,因为 python for 循环等同于其他语言上的 for each 循环和为您遍历列表,而不是依靠一个值来获取列表元素,例如yourlist[value]

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 1970-01-01
      • 2021-12-11
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      相关资源
      最近更新 更多