3 回答

TA贡献1111条经验 获得超0个赞
您还应该知道,在Python中,遍历整数索引是不好的样式,并且比替代方法要慢。如果您只想查看列表或字典中的每个项目,请直接在列表或字典中循环。
mylist = [1,2,3]
for item in mylist:
print item
mydict = {1:'one', 2:'two', 3:'three'}
for key in mydict:
print key, mydict[key]
实际上,这比将上面的代码与range()结合使用要快,并且可以删除无关的i变量。
如果需要就地编辑列表项,则确实需要索引,但是还有更好的方法:
for i, item in enumerate(mylist):
mylist[i] = item**2
同样,这既更快又更易读。从C ++到Python时,这是思想上的主要转变之一。

TA贡献1864条经验 获得超6个赞
答案是好的,但是对于想要使用的人来说,要做range()的表格是:
range(end):
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(start,end):
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range(start,end, step):
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
添加回答
举报