简体   繁体   中英

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]. 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

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. 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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