简体   繁体   中英

Why does it not print a list of tuples with no repeated tuples?

So I made a function that goes through a list of tuples that contains the maker of a car, city mpg, and highway mpg.

def maker(mileage_list):
    maker_list = []
    for line in mileage_list:
        if line[2] not in maker_list:
            maker_tuple = (line[2],int(line[0]),int(line[1]))
            maker_list.append(maker_tuple)
    return maker_list

Where if

mileage_list = [('DODGE', 13, 18), ('DODGE', 16, 22), 
                ('DODGE', 16, 22), ('DODGE', 16, 21), 
                ('FORD', 16, 24), ('FORD', 20, 26), 
                ('FORD', 22, 28), ('FORD', 18, 24), 
                ('FORD', 34, 30), ('FORD', 12, 18)]

it should only print maker_list =[('DODGE',13,18),('FORD',16,24)] but it still prints out the original input.

line[2] will never be in mileage_list because it is a string, and the items in mileage_list are tuples, and the two will never be equal. Therefore it will always add each item. Also, line[2] is your highway MPG (as a string), not the maker, so even if it worked the way you wanted, it still would have a lot of duplicates.

I would use a separate set to keep track of the makers you've seen.

def maker(mileage_list):
    maker_set = set()
    maker_list = []
    for maker, city_mpg, hwy_mpg in mileage_list:
        if maker not in maker_set:
            maker_list.append((maker, int(city_mpg), int(hwy_mpg))
            maker_set.add(maker)
    return maker_list

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