【问题标题】:Mutating list in pythonpython中的变异列表
【发布时间】: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 的回答中理解了。

标签: python list mutation


【解决方案1】:
def initialize_one(seq, n):
    if not seq:
        seq[:] = [1] * n

【讨论】:

    猜你喜欢
    • 2020-03-25
    • 2017-06-24
    • 2021-06-28
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    相关资源
    最近更新 更多