python中的突变列表 [英] Mutating list in python
本文介绍了python中的突变列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想定义一个函数,该函数可以通过在其中添加1的([1,1,1,...])来使输入列表发生变化. 但是,我不想使用循环来执行此简单操作.
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]
推荐答案
def initialize_one(seq, n):
if not seq:
seq[:] = [1] * n
这篇关于python中的突变列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文