python-3.x - 从一对对应列表中删除重复项
问题描述
这是我最近制作的一个程序。这段代码的目标是一对对应的列表。所以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)
解决方案
首先让我们分析代码中的 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]
.
推荐阅读
- android - 如何使用 Firebase 将毕加索图像添加到 ArrayList
- xslt - 创建 html 表时避免重复
- nativescript - 当应用程序在 android 平台的前台时,Firebase 推送通知不显示
- php - Symfony:在 FormType 表单中为 EntityType 使用不同的字段
- selenium - 在命令提示符下运行 selenium 测试套件时有等待/超时
- javascript - 在 react 和 JavaScript 中获取正确格式的数据
- javascript - 在 MS Edge 中检测覆盖模式
- julia - 在 Julia/DifferentialEquations 中使用 VectorContinuousCallback 时输出解中事件的索引
- .net - Zip 文件的文件类型在复制到 AWS S3 时发生变化
- android - 使用 adb 和活动管理器在 Android 上捕获具有指定名称的 JPEG 图像