【发布时间】:2013-06-12 11:07:21
【问题描述】:
我想定义一个函数,它可以通过添加 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]
【问题讨论】:
-
检查相等时请不要使用
is -
只是出于好奇,为什么需要这样的功能?
empty_lis = [1] * 100更具可读性和更短。 -
@Blender 我还想为 union 定义一个函数,它接受两个列表,并且该函数将改变第一个列表。比如 a = list(set(a) | set(b))
-
@BalaKrishnan:那你为什么不使用集合呢?
-
@Blender 实际上我不知道如何改变列表,但现在我从 jamyalk 的回答中理解了。