【问题标题】:replacing an item in a circular list [duplicate]替换循环列表中的项目[重复]
【发布时间】:2020-04-23 00:20:24
【问题描述】:

所以我需要做的任务是创建一个可以替换循环列表中的项目的类。

例如,如果

MyList = [0, 1, 2, 3, 4]

MyList[100] = 6

这需要返回

MyList = [6, 1, 2, 3, 4] 

关于如何进行设置的任何提示?

【问题讨论】:

  • 欢迎来到 StackOverflow。我们不是来帮你做作业的,所以请向我们展示你的尝试,以便我们提供帮助!
  • 我认为您可能正在寻找的是“循环链表”

标签: python circular-list


【解决方案1】:

好吧,假设 100 预计会根据列表大小进行修改(取模),您可以使用如下内容:

def replaceModulo(the_list, the_index, the_value):
    the_list[the_index % len(the_list)] = the_value

但是最好有一个适当封装的类来执行此操作,以便使用它的代码具有非常特定的 API,并且您可以随意修改底层代码,例如,如果您找到了更好的方法.

该类将维护固定大小列表以及头部和尾部/大小,并提供标准操作以及您想要的 replace

que = createCircularQueue(sz)
que.push(item)
item = que.pop()
old_value = que.replace_at(idx, new_value)

这样,所有将idx转换为实际索引的代码(它取决于head)都会被隐藏起来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-06
    • 2011-11-05
    • 2020-06-08
    • 2015-12-06
    • 2019-12-02
    • 2018-01-02
    • 2011-03-11
    • 2019-02-25
    相关资源
    最近更新 更多