在Python3中解压缩迭代?

时间:2017-03-09 12:43:04

标签: list python-3.x tuples iterable-unpacking

为什么返回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))

当我注释掉第二个for循环时,它会打印元组:

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

输出:

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

所以,元组在那里。他们为什么不打开自己的包装?

1 个答案:

答案 0 :(得分:3)

你的第二个for循环是循环元组中的项目,但是你正在抓取其中的两个项目。我想这就是你想要的:

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