简体   繁体   English

列表理解ValueError:太多值无法解包

[英]List comprehension ValueError: too many values to unpack

I have a process which generates 2-item lists as [datestamp, timestamp] . 我有一个生成2项列表的过程,如[datestamp, timestamp]

if I put this into a list comprehension as: 如果我将其放入列表理解为:

[(ds,ts) for ds,ts in process]

my desired outcome is: 我期望的结果是:

[(ds,ts), (ds,ts), (ds,ts)]

What I get is ValueError: too many values to unpack . 我得到的是ValueError: too many values to unpack

This is because the for loop iteration into the list returned by the process: 这是因为for循环迭代到该进程返回的列表中:

for ds,ts in [datestamp, timestamp]

does not assign ds=datestamp , ts=timestamp , but rather iterates across each letter ... if this worked it would give (d,t) , (a,i) , (t,m) , (e,e) etc 不分配ds=datestampts=timestamp ,而是遍历每个字母...如果这样做有效,它将给出(d,t)(a,i)(t,m)(e,e)

So I know what's wrong ... but not how to make this work! 所以我知道出了什么问题...但是不知道如何完成这项工作! (and yeah, this does feel silly ... I know the answer will be real simple (是的,这确实很愚蠢……我知道答案会很简单

This works: 这有效:

process = [[1,2],[3,4],[5,6]]
a = []
for ds, ts in process:
    print(ds, ts)
    a.append((ds, ts))

As well as 以及

z = [(ds, ts) for (ds, ts) in process]
q = [(ds, ts) for ds, ts in process]

If you are getting a 'ValueError: too many values to unpack' exception, process must be producing iterables that have more than two items. 如果收到'ValueError: too many values to unpack'异常,则流程必须生成具有两个以上项目的可迭代对象。

Unwind the list comprehension and Handle the exception - print something relevant in the except suite to see what might be going wrong, then work backwards to the source. 解开列表理解并处理异常 -在except套件中打印相关内容以查看可能出了什么问题,然后向后处理源代码。 something like 就像是

process = [[1,2],[3,4],[5,6], [7,8,9]]

a = []
try:
    for thing in process:
        ds, ts = thing
        a.append((ds, ts))
except ValueError as e:
    print(e, '\t', thing)

You need to debug. 您需要调试。 There must be some items in your list that are not pairs as you expect. 您的列表中一定有一些项目不是您期望的成对的。

One way you can find them would be: 找到它们的一种方法是:

problems = [(idx, value) for idx,value in enumerate(process) if len(value)!=2]

This will give you a list of the problem indexes and items in your list. 这将为您提供问题索引列表以及列表中的项目。

If that gives an error- for example, a TypeError because the value object has no __len__ method- then change it to: 如果出现错误(例如,由于value对象没有__len__方法而导致TypeError ,则将其更改为:

problems = [(idx, value) for idx,value in enumerate(process) if not hasattr(value, '__len__')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM