如何在不使用for-loop的情况下将值附加到列表中?
我想避免在这段代码中使用循环:
count = []
for i in range(0, 6):
print "Adding %d to the list." % i
count.append(i)
结果必须是:
count = [0, 1, 2, 3, 4, 5]
我尝试了不同的方法,但我无法做到。
答案 0 :(得分:7)
因为range
会返回一个列表,您只需执行
>>> count = range(0,6)
>>> count
[0, 1, 2, 3, 4, 5]
其他避免循环的方法(docs):
>>> count = [1,2,3]
>>> count.extend([4,5,6])
>>> count
[1, 2, 3, 4, 5, 6]
相当于count[len(count):len(count)] = [4,5,6]
,
和functionally与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]
(从2到3的count
切片被可迭代的内容替换为右边)
答案 1 :(得分:5)
使用list.extend
:
>>> count = [4,5,6]
>>> count.extend([1,2,3])
>>> count
[4, 5, 6, 1, 2, 3]
答案 2 :(得分:3)
您可以使用范围功能:
>>> range(0, 6)
[0, 1, 2, 3, 4, 5]
答案 3 :(得分:3)
对于没有extend
...
>>> lst = [1, 2, 3]
>>> lst
[1, 2, 3]
>>> lst += [4, 5, 6]
>>> lst
[1, 2, 3, 4, 5, 6]
答案 4 :(得分:0)
List comprehension
>>> g = ['a', 'b', 'c']
>>> h = []
>>> h
[]
>>> [h.append(value) for value in g]
[None, None, None]
>>> h
['a', 'b', 'c']
答案 5 :(得分:0)
您始终可以使用递归替换循环:
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]