如何在不使用 for 循环的情况下将值附加到列表?
我想避免在这段代码中使用循环:
count = []
for i in range(0, 6):
print "Adding %d to the list." % i
count.append(i)
结果必须是:
count = [0, 1, 2, 3, 4, 5]
我尝试了不同的方法,但我无法做到。
如何在不使用 for 循环的情况下将值附加到列表?
我想避免在这段代码中使用循环:
count = []
for i in range(0, 6):
print "Adding %d to the list." % i
count.append(i)
结果必须是:
count = [0, 1, 2, 3, 4, 5]
我尝试了不同的方法,但我无法做到。
since range
returns a list you can simply do
>>> count = range(0,6)
>>> count
[0, 1, 2, 3, 4, 5]
Other ways to avoid loops (docs):
>>> count = [1,2,3]
>>> count.extend([4,5,6])
>>> count
[1, 2, 3, 4, 5, 6]
Which is equivalent to count[len(count):len(count)] = [4,5,6]
,
and functionally the same as count += [4,5,6]
.
>>> count = [1,2,3,4,5,6]
>>> count[2:3] = [7,8,9,10,11,12]
>>> count
[1, 2, 7, 8, 9, 10, 11, 12, 4, 5, 6]
(slice of count
from 2 to 3 is replaced by the contents of the iterable to the right)
使用list.extend
:
>>> count = [4,5,6]
>>> count.extend([1,2,3])
>>> count
[4, 5, 6, 1, 2, 3]
对于没有extend
...的答案
>>> lst = [1, 2, 3]
>>> lst
[1, 2, 3]
>>> lst += [4, 5, 6]
>>> lst
[1, 2, 3, 4, 5, 6]
You could just use the range function:
>>> range(0, 6)
[0, 1, 2, 3, 4, 5]
列表理解
>>> g = ['a', 'b', 'c']
>>> h = []
>>> h
[]
>>> [h.append(value) for value in g]
[None, None, None]
>>> h
['a', 'b', 'c']
您总是可以用递归替换循环:
def add_to_list(_list, _items):
if not _items:
return _list
_list.append(_items[0])
return add_to_list(_list, _items[1:])
>>> add_to_list([], range(6))
[0, 1, 2, 3, 4, 5]