2

我想定义一个函数,它可以通过添加 1's([1,1,1,...]) 来改变输入的列表。但是,我不想使用循环来执行这个简单的操作。

# input - a list (empty list)
#       - number of elements to initialize
# output- None
#       - But it will have to mutate the inputted (list)
def initialize_one(empty_lis, n):
    # Do nothing if e_lis is a non-empty list
    if len(empty_lis) is not 0:
        return
    else:
        temp = [1] * n
        # empty_lis = temp will not mutate
        # And I don't want to use loops to append
        # because if n = 100,000
        # it will have to loop for 100,000 times


lis = []
n = 10
initialize_one(lis, n)

print lis
# expected output
# >>>[1, 1, 1, 1, 1, 1, 1, 1, 1]
4

1 回答 1

3
def initialize_one(seq, n):
    if not seq:
        seq[:] = [1] * n
于 2013-06-16T08:40:59.850 回答