【问题标题】:Why it says ValueError for the below program with python3 but not python2为什么下面的程序使用 python3 而不是 python2 时显示 ValueError
【发布时间】:2018-09-09 03:35:56
【问题描述】:
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)

【问题讨论】:

    标签: python-3.x python-2.7 dictionary hashtable


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
      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
      

      在 python 3.x 中,您的 zip 现在是空的。因此错误

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

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

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

      【讨论】:

        猜你喜欢
        • 2019-06-04
        • 1970-01-01
        • 2018-02-15
        • 1970-01-01
        • 2011-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-28
        相关资源
        最近更新 更多