2

如何在不使用 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]

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

4

6 回答 6

8

Range:

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):

Extend:

>>> 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].

Slice:

>>> 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)

于 2013-08-24T10:26:41.583 回答
6

使用list.extend

>>> count = [4,5,6]
>>> count.extend([1,2,3])
>>> count
[4, 5, 6, 1, 2, 3]
于 2013-08-24T10:19:42.250 回答
4

对于没有extend...的答案

>>> lst = [1, 2, 3]
>>> lst
[1, 2, 3]
>>> lst += [4, 5, 6]
>>> lst
[1, 2, 3, 4, 5, 6]
于 2013-08-24T10:38:57.657 回答
3

You could just use the range function:

>>> range(0, 6)
[0, 1, 2, 3, 4, 5]
于 2013-08-24T10:26:28.357 回答
1

列表理解

>>> g = ['a', 'b', 'c']
>>> h = []
>>> h
[]
>>> [h.append(value) for value in g]
[None, None, None]
>>> h
['a', 'b', 'c']
于 2015-06-25T18:23:11.737 回答
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]
于 2015-08-17T14:17:29.290 回答