Python:将值附加到列表而不使用for循环

Python: Append values to list without for-loop

如何在不使用for循环的情况下将值附加到列表中?

我想避免在这段代码中使用循环:

1
2
3
4
count = []
for i in range(0, 6):
    print"Adding %d to the list." % i
    count.append(i)

结果必须是:

1
count = [0, 1, 2, 3, 4, 5]

我尝试了不同的方法,但我做不到。


Range:

由于range返回一个列表,您只需

1
2
3
>>> count = range(0,6)
>>> count
[0, 1, 2, 3, 4, 5]

避免循环(docs)的其他方法:

扩展:

1
2
3
4
>>> count = [1,2,3]
>>> count.extend([4,5,6])
>>> count
[1, 2, 3, 4, 5, 6]

相当于count[len(count):len(count)] = [4,5,6]

在功能上与count += [4,5,6]相同。

切片:

1
2
3
4
>>> 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切片被右边的iterable内容替换)


使用list.extend

1
2
3
4
>>> count = [4,5,6]
>>> count.extend([1,2,3])
>>> count
[4, 5, 6, 1, 2, 3]


不带extend的答案…

1
2
3
4
5
6
>>> lst = [1, 2, 3]
>>> lst
[1, 2, 3]
>>> lst += [4, 5, 6]
>>> lst
[1, 2, 3, 4, 5, 6]


您可以使用范围函数:

1
2
>>> range(0, 6)
[0, 1, 2, 3, 4, 5]


始终可以用递归替换循环:

1
2
3
4
5
6
7
8
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]

列表理解

1
2
3
4
5
6
7
8
>>> g = ['a', 'b', 'c']
>>> h = []
>>> h
[]
>>> [h.append(value) for value in g]
[None, None, None]
>>> h
['a', 'b', 'c']