I have a process which generates 2-item lists as [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
.
This is because the for
loop iteration into the list returned by the process:
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
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.
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. 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:
problems = [(idx, value) for idx,value in enumerate(process) if not hasattr(value, '__len__')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.