【问题标题】:Get collection index to cycle back around获取集合索引以循环返回
【发布时间】:2021-07-23 05:04:15
【问题描述】:

当使用诸如 python 列表之类的集合时,有没有办法让我的索引“连续”?例如说我有以下列表:

list=[0,1,2,3]

现在这里list[3]=3list[4] 没有定义...是否可以设置我的收藏以便它们循环返回,以便list[4]=0, list[8]=0..., list[280]=0...,即使我的列表仍然只包含这4 个元素?

【问题讨论】:

  • 您可以使用模运算。例如:lst[4 % len(lst)]

标签: python arrays list collections


【解决方案1】:

这就是你可以做到的。如果你 .init 一次类,那么更改就会完成。

class list_no_stop(list):
  def __getitem__(self,i):
      return list(self)[i % len(self)]
  def __setitem__(self,x,i):
     nv=list(self)
     nv[x % len(self)]=i         
     self.clear()
     self.extend(nv)
newlist=list_no_stop([1,2,3,5])
print(newlist[100])
#print(newlist[11])
newlist[11]=80
#newlist[12]=1000

newlist[12]=1000
print(newlist)

【讨论】:

    猜你喜欢
    • 2010-12-06
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多