Unpacking iterables in Python3?

2019-09-12 19:45发布

问题:

Why is this returning in sort_tup_from_list for key, val in tup: ValueError: not enough values to unpack (expected 2, got 1)

# list with tuples
lst = [("1", "2"), ("3", "4")]

# sorting list by tuple val key
def sort_tup_from_list(input_list):
    tmp = []
    print(tup)
    for tup in input_list:
        for key, val in tup:
            tmp.append((val, key))
            tmp.sort(reverse=True)
    return tmp

print(sort_tup_from_list(lst))

When I comment out second for loop, it prints tuple:

lst = [("1", "2"), ("3", "4")]
def sort_tup_from_list(input_list):
    tmp = []
    for tup in input_list:
        print(tup)
        # for key, val in tup:
        #     tmp.append((val, key))
        #     tmp.sort(reverse=True)
    return tmp

print(sort_tup_from_list(lst))

Output:

('1', '2')
('3', '4')
[]

So, tuples are there. Why are they not unpacking themselfs?

回答1:

Your second for loop is looping through items in the tuple, but you're grabbing both of the items in it. I think this is what you want:

# list with tuples
lst = [("1", "2"), ("3", "4")]

# sorting list by tuple val key
def sort_tup_from_list(input_list):
    tmp = []
    print(tmp)
    for key,val in input_list:
        tmp.append((val, key))
        tmp.sort(reverse=True)
    return tmp

print(sort_tup_from_list(lst))