【问题标题】:How to stop loop at limit, if limit is given. How to return new list with appended values?如果给定了限制,如何在限制处停止循环。如何返回带有附加值的新列表?
【发布时间】:2017-03-25 21:52:08
【问题描述】:

我正在构建一个接受四个参数的函数:xs(original list)oldnewlimit=None)。如果旧数字在列表中,则给定一个特定值(old),将其替换为新值并返回一个名为 new_xs 的新列表。

第四个参数limit是一个整数,表示允许的最大替换次数。我只需要替换old 的第一个限制出现,其余的保持不变。当limit==None 时,确实没有限制(我替换所有出现的old)。
负限或零限:不可替代

输入/输出示例:

xs=[1,2,3,4,5]
old= 2
new=100
new_xs=[1,100,3,4,5]


def replace(xs, old, new, limit=None):
    new_xs=[]
    for num in range(len(xs)):
        if num==old:
            new_xs.append(new)
    return new_xs

如果有限制,我不确定如何让它停在限制处。

【问题讨论】:

  • 请完整的堆栈跟踪。该代码不能抛出 indexerror
  • 什么是完整的堆栈跟踪?抱歉,我是编程新手
  • 运行程序时的输出副本。
  • >>> replace(xs, old, new, limit=None) Traceback(最近一次调用最后):文件“”,第 1 行,在 文件“ ",第 5 行,在替换 IndexError: list index out of range >>> def replace(xs, old, new, limit=None): ... new_xs=[] ... for num in range(len(xs) ): ... if num ==old: ... new_xs.append(xs[new]) ... return new_xs >>> replace(xs, old, new, limit= None) Traceback (最近一次调用最后一次) :文件“”,第 1 行,在 文件“”,第 5 行,替换 IndexError: list index out of range
  • new_xs.append(xs[new]): 这不是你发布的代码!!由于new=100xs 的大小要小得多,因此存在索引错误。

标签: python list function append


【解决方案1】:

我冒昧地更改了您的代码,只是替换了您列表中的值,然后将其返回。请注意,这不会更改原始列表。

def replace(xs, old, new, limit=None):
    for index,value in enumerate(xs):
        if value==old:
            xs[index]=new
    return xs

基本上,它会检查您提供给它的列表中的值,然后如果它与旧值匹配,它会将其更改为新值。 enumerate() 只计算您执行的每次迭代以及提供列表中的值,因此我可以使用该值来查找旧值在列表中的位置,然后将其换出。

因此,使用 xs、新、旧的值:

xs=[1,2,3,4,5]
old= 2
new=100

new_xs = replace(xs, old, new)

然后print(new_xs) 给出: [1, 100, 3, 4, 5]

请注意,我没有为您实施限制,因此目前没有任何作用。

【讨论】:

  • 如何实现限制?
  • 您觉得这个答案比我的答案更正确有什么具体原因吗?真的很好奇。
  • 它实际上是根据需要执行的。
  • 我无法在我的测试用例中使用 limit=float("inf")):
  • 啊,我明白了。我会尝试另一种方式。
【解决方案2】:

几个问题:

  1. 您正在循环 range() 的输出,这是一个新的整数序列,而不是 xs 的内容。我们可以直接循环 xs 来获取我们想要的值。

  2. 您目前仅在条件匹配时将值附加到新的 xs_new 列表中,而我们希望每次都附加一个值。

  3. 您指定的限制功能未实现。


代码cmets中的解释:

def replace(xs, old, new, limit=None): 
    new_xs = []
    replacements = 0 # keep track of how many times we replace
    for num in xs:
        if num == old and (limit is None or replacements < limit):
            new_xs.append(new)
            replacements += 1
        else:
            new_xs.append(num) # appened the original value if no match
    return new_xs

print replace(xs, old, new)

一些示例输入/输出:

>>> xs = [1, 2, 3, 4, 5]
>>> old = 2
>>> new = 100
>>> replace(xs, old, new)
[1, 100, 3, 4, 5]

>>> xs = [1, 2, 3, 4, 5, 2, 2]
>>> old = 2
>>> new = 100
>>> limit = 2
>>> replace(xs, old, new, limit)
[1, 100, 3, 4, 5, 100, 2]

【讨论】:

  • 是否会将参数 limit=None 更改为您更改的内容以影响它在我的测试器代码中的运行方式?
  • 是的,因为None 总是小于任何int
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
相关资源
最近更新 更多