Unpacking iterables in Python3?

有些话、适合烂在心里 提交于 2019-12-12 02:09:38

问题


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


来源:https://stackoverflow.com/questions/42695716/unpacking-iterables-in-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!