Python - 解压的值太多 [英] Python - too many values to unpack

查看:29
本文介绍了Python - 解压的值太多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字符串和字符串列表的元组,如下所示:

I have a tuple containing string and a list of string as below:

test = ('str1',['1', '2'])
for a,b in test:
    print(a,b)

我想以一种可以得到[('str1','1'),('str1','2')]的方式解压.

I want to unpack in a way that I can get [('str1','1'),('str1','2')].

但是我收到ValueError:解压的值太多(预期为 2)".

如果我打印测试长度,则为 2.所以不确定这里有什么问题.

If I print length of test, it comes as 2. So not sure what is wrong here.

推荐答案

虽然 test 有两个元素,但您正在尝试迭代元组,因为 test 没有元组(它本身就是一个元组).

Although test has two elements, you're attempting to iterate over tuples which won't work because test has no tuples (it's a tuple itself).

所以这是有效的:

test = [('str1',['1', '2'])]
for a,b in test:
    print(a,b)

或者,为了得到你想要的,作为一个列表:

Or, to get what you want, as a list:

print([(test[0], item) for item in test[1]])

你也可以这样迭代:

test = ('str1',['1', '2'])
for item in test[1]:
    print(test[0], item)

这篇关于Python - 解压的值太多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆