[英]Unpacking error
lstOfitems= list(leterCount.values())
HstNumber = max(lstOfitems)
ListOfkeys= list(leterCount.keys())
NumberofChar = len(ListOfkeys)
tess = turtle.Turtle()
tess.color("white")
tess.fillcolor("white")
tess.pensize(3)
wn = turtle.Screen()
wn.bgcolor("black")
wn.setworldcoordinates(0-BORDER,0-BORDER,FORWARD*NumberofChar+BORDER,HstNumber+BORDER)
for a,b in(lstOfitems,ListOfkeys):
drawBar(tess, a, b)
The above code takes in a string and counts how many charters there are and stores then in a dictionary. 上面的代码接受一个字符串,计算有多少章程,然后存储在字典中。 I'm trying to then make a bar chart after that but i run in to the problem where i get an error saying there are to vaules to unpack.
我试图在那之后做一个条形图,但我遇到了一个问题,我得到一个错误说有vaules解包。 How do i fix this ?
我该如何解决 ?
the trace back is this : 回溯是这样的:
Traceback (most recent call last):
File "C:\\Users\\Steven\\Desktop\\lab8excirse2.py", line 76, in main() File "C:\\Users\\Steven\\Desktop\\lab8excirse2.py", line 74, in main loopSTr() File "C:\\Users\\Steven\\Desktop\\lab8excirse2.py", line 47, in loopSTr for a,b in(lstOfitems,ListOfkeys): ValueError: too many values to unpack (expected 2) 文件“C:\\ Users \\ Steven \\ Desktop \\ lab8excirse2.py”,第76行,在main()文件“C:\\ Users \\ Steven \\ Desktop \\ lab8excirse2.py”,第74行,在main loopSTr()文件“C中:\\ Users \\ Steven \\ Desktop \\ lab8excirse2.py“,第47行,在loopSTr中为a,b in(lstOfitems,ListOfkeys):ValueError:要解压的值太多(预期2)
I think, you want something like this: 我想,你想要这样的东西:
for b,a in leterCount.items():
drawBar(tess, a, b)
Try changing (lstOfitems,ListOfkeys)
to zip(lstOfitems,ListOfkeys)
. 尝试将
(lstOfitems,ListOfkeys)
更改为zip(lstOfitems,ListOfkeys)
。 (lstOfitems,ListOfkeys)
is simply a tuple
consisting of two list
s, you cannot unpack it. (lstOfitems,ListOfkeys)
只是一个由两个list
组成的tuple
,你无法解压缩它。 However, Python's built-in zip
function will return an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables; 但是,Python的内置
zip
函数将返回元组的迭代器,其中第i个元组包含来自每个参数序列或迭代的第i个元素; which is what you want. 这就是你想要的。
But a better way to do this is to access the dictionary keys/value pairs using the dictionary's 'items method:
for b,a in leterCount.items():` 但更好的方法是使用字典的'items
method:
访问字典键/值对method:
对于b,在leterCount.items()中:
Having said that, are you aware that Python collections
has a dict
sub-class called Counter
that does pretty much what you want? 话虽如此,您是否意识到Python
collections
有一个名为Counter
的dict
子类,它可以完成您想要的任务? You can use it like so: 您可以像这样使用它:
from collections import Counter
c = Counter('gallahad') # a new counter from an iterable
# c will then be: Counter({'a': 3, 'l': 2, 'h': 1, 'g': 1, 'd': 1})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.