为什么它使用python3而不是python2为下面的程序说ValueError

时间:2020-12-11 18:26:34
k=['d','e','f']
v=[4,5,6]
h=zip(k,v)      #zipping
for i,j in h:
  print(i ,':',j)
(k,v)=zip(*h)   #unzipping
print(k)
print(v)
output:

Traceback (most recent call last):

 File "hasht.py", line 6, in <module>
    (k,v)=zip(*h)

ValueError: not enough values to unpack (expected 2, got 0)

2 个解决方案

#1


0  

zip creates a list in Python 2, so your h is a value that you can inspect at any time. zip creates an iterator in Python 3, so your loop with the print statement exhausts h.

zip在Python 2中创建一个列表,因此您的h是一个可以随时检查的值。 zip在Python 3中创建了一个迭代器,因此使用print语句的循环耗尽了h。

Use h = list(zip(k, v)) to get the same behavior in both Python 2 and 3.

使用h = list(zip(k,v))在Python 2和3中获得相同的行为。

#2


0  

k=['d','e','f']
v=[4,5,6]
h=zip(k,v)      #zipping
zip_list=list(h)
for i,j in h:
  print(i ,':',j)
type(h)
h

Here your zip is now empty in python 3.x. Hence the error

(k,v)=zip(*h)   #unzipping on empty object
print(k)
print(v)

You can still iterate on zip_list object created multiple times

您仍然可以迭代多次创建的zip_list对象

for m,n in zip_list:
   print (m,n)

#1


0  

zip creates a list in Python 2, so your h is a value that you can inspect at any time. zip creates an iterator in Python 3, so your loop with the print statement exhausts h.

zip在Python 2中创建一个列表,因此您的h是一个可以随时检查的值。 zip在Python 3中创建了一个迭代器,因此使用print语句的循环耗尽了h。

Use h = list(zip(k, v)) to get the same behavior in both Python 2 and 3.

使用h = list(zip(k,v))在Python 2和3中获得相同的行为。

#2


0  

k=['d','e','f']
v=[4,5,6]
h=zip(k,v)      #zipping
zip_list=list(h)
for i,j in h:
  print(i ,':',j)
type(h)
h

Here your zip is now empty in python 3.x. Hence the error

(k,v)=zip(*h)   #unzipping on empty object
print(k)
print(v)

You can still iterate on zip_list object created multiple times

您仍然可以迭代多次创建的zip_list对象

for m,n in zip_list:
   print (m,n)