Geo*_*ows 3 python indexing list histogram traceback
我有一个整数百分比列表,我需要使用以下模式打印:
Run Code Online (Sandbox Code Playgroud)The index of a value, a tab (8 spaces), a '*' printed for each percentage point
如果索引的值为0,则打印'小于1%'
我试过这段代码:
for b in new_tally:
if b > 0:
print new_tally[b], \t, '*' * b
else:
print 'Less than 1% of words had this length'
Run Code Online (Sandbox Code Playgroud)
但是我一直收到错误代码:列表索引超出范围.
我根本不明白这一点,有人能指出我做错了什么吗?
我认为你想要的代码是:
>>> new_tally = [5, 7, 8, 6, 4, 2]
>>> for i, b in enumerate(new_tally, 1):
print i, ':', b, '*' * b
1 : 5 *****
2 : 7 *******
3 : 8 ********
4 : 6 ******
5 : 4 ****
6 : 2 **
Run Code Online (Sandbox Code Playgroud)
原始回溯的原因是使用方括号而不是括号查找列表成员. new_tally(i)是一个函数调用. new_tally[i]是一个索引查找.