简体   繁体   English

Python:比较列表中的值

[英]Python: Comparing values within a list

I have a list in my python program, I am wanting to compare each value in the list to every other value and if the values are equal to each other then print the iterative value in the list eg ages[1].我的 python 程序中有一个列表,我想将列表中的每个值与其他所有值进行比较,如果这些值彼此相等,则在列表中打印迭代值,例如年龄 [1]。 Here is the codes so far这是到目前为止的代码

ages = [16, 16, 15]
for i in ages:
    for x in ages:
        if i == x:
            print(i, "=", x)

Currently this is giving me an output of目前这给了我一个 output

16 = 16
16 = 16
16 = 16
16 = 16
15 = 15

I understand that it is comparing each value in the list without the omission of the values already dealt with as well as that the print function is only giving the current value of the iteration.我知道它正在比较列表中的每个值,而没有省略已经处理的值,并且打印 function 仅给出迭代的当前值。 Is there any solution to this?有什么解决办法吗?

This will not repeat any comparisons这不会重复任何比较

ages = [16, 16, 15]
l = len(ages)
for i in range(l):
    for x in range(i+1,l): # range(i+1,l) makes sure that you don't compare with itself OR repeat any comparisons
        if ages[i] == ages[x]:
            #print(ages[i], "=", ages[x])
            print("ages[{}] = ages[{}]".format(i, x))
ages[0] = ages[1]

One way to do it would be to use enumerate :一种方法是使用enumerate

ages = [16, 16, 15]
for i, x in enumerate(ages):
    for j, y in enumerate(ages[i+1:]):
        if x == y:
            print(f"{i}/{i + 1 + j}: {x}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM