范围'函数可以赋值给列表吗?
我正在学习《艰难的Python学习法》这本PDF。在第82页我遇到了这个问题。
- 你能否完全避免在第23行使用for循环,而是直接把range(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
看起来如果不使用map函数,这个是做不到的,对吗?
5 个回答
2
这个提示可能是想告诉你,其实你可以直接使用
elements = range(6)
这样做也能得到一样的结果。
4
不过你也可以进行相当复杂的赋值操作。
elements = [0,1,2,3,4,5,6,7,8,9,10]
elements[3:5] = range(10,12) # replace indexes 3 and 4 with 10 and 11.
elements[3:7:2] = range(100,201,100) replace indexes 3 and 5 with 100 and 200
elements[:] = range(4) # replace entire list with [0,1,2,3]
[start,end,by] 这种写法叫做切片。Start 是开始的索引(包括这个位置,默认是 0)。End 是结束的索引(不包括这个位置,默认是列表的长度)。By 是从一个索引移动到下一个索引的步长(默认是 1)。
10
在Python 2.x版本中,range
会返回一个列表。而在3.x版本中,它返回的是一个可迭代的范围对象。你总是可以使用list(range(...))
来得到一个列表。
不过,for x in y
并不要求y
是一个列表,只要是一个可迭代的对象就可以了,比如xrange
(只有在2.x中有)、range
、list
、str
等等。