可以将"范围"功能分配给列表吗?

0 python

我正在学习学习Python的艰难之路 PDF.在页82上我遇到了这个问题.

  • 你能完全避免第23行的for循环,只是将范围(0,6)直接分配给元素吗?

鉴于代码:

# we can also build lists, first start with an empty one
elements = []

# then use the range function to do 0 to 20 counts
for i in range(0, 6):
    print "Adding %d to the list." % i    # line 23
    # append is a function that lists understand
    elements.append(i)

# now we can print them out too
for i in elements:
    print "Element was: %d" % i
Run Code Online (Sandbox Code Playgroud)

除非我使用地图功能,否则这似乎是不可能的?我对么?

phi*_*hag 10

在python 2.x中,range返回一个列表.在3.x中,它返回一个可迭代范围对象.您可以随时使用list(range(...))获取列表.

然而,for x in y并不要求y是一个列表,只是一个迭代(例如xrange(仅2.X) ,,range ,...)liststr