Mutating list in python

╄→гoц情女王★ 提交于 2019-12-10 10:45:25

问题


I want to define a function which can mutate the inputted list by adding 1's([1,1,1,...]) in to it. But, I don't want to use loops to perform this simple operation.

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

回答1:


def initialize_one(seq, n):
    if not seq:
        seq[:] = [1] * n


来源:https://stackoverflow.com/questions/17131536/mutating-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!