列表索引 - 如果太大,请返回列表的开始



所以,也许这个问题听起来很开头,但是我只是不知道我应该如何从这个示例开始:

所以示例是:我有一个清单,例如13个项目(1,2,3,4 ... 13(有一个给定的数字,假设6

该程序需要在列表中显示我的数字将以什么顺序显示。如果第二个数字为6,则意味着每次第六项是下一个WHCIH都会掉下来的。但是我的问题是,我怎么能告诉python,如果索引编号升高过高,它应该从开始的开始重新计数?

这是我到目前为止我自己的原因

x = int(input("Number of items (numbers): "))
y = int(input("Fall-out number: "))
#n = 1
#id = 0
numbers = [n for n in range(x+1)]
fallsout = []
numbers.remove(30)
for i in numbers:
    if i % y == 0:
        fallsout.append(i)
print (numbers)
print (fallsout)

这是一个示例,输入和输出中应该是什么:

输入:x = 13y = 6

输出:6 12 5 13 8 3 1 11 2 7 4 10 9

好吧,看起来您想将每个6个元素从数字复制到辐射,然后从数字中删除元素,然后以循环方式继续直到数字为空。

import copy
x = int(input("Number of items (numbers): "))
y = int(input("Fall-out number: "))
# list should start from 1 as by the example
numbers = [n for n in range(1,x+1)]
# deep copy to preserve original list
numbers_copy = copy.deepcopy(numbers)
fallsout = []
count = y
while len(numbers_copy)!=0:
    fallsout.append(numbers_copy[count-1])
    # remove element
    del numbers_copy[count-1]
    # handle starting edge
    if count == 0:
        count = 1
    # handle last edge
    if numbers_copy != []:
        count = (count+y-1)%len(numbers_copy)
print numbers
print fallsout

输出是

Number of items (numbers): 13
Fall-out number: 6
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[6, 12, 5, 13, 8, 3, 1, 11, 2, 7, 4, 10, 9]

说明

假设我的数组数= [1,2,3,4,5,6]的长度= 6,并且我正在使用计数器"计数"来通过列表进行迭代。这样,

数字[count] = 2(当count = 1(

然后查看下一个元素,我将使用数字[count 1]。要跳回列表的开始,我们使用模量操作,

count =(count number_of_steps(%len(数字(

eg,在索引= 4并跳3步,下一个索引将为(4 3(%6 = 1现在,我们必须从列表中复制每个rth元素,因此我们使用

fallsout.append(numbers_copy[count-1]) # count-1 as we are counting from 0

然后我们从列表中删除该号码,

del numbers_copy[count-1]

然后,我们按模量通过y步骤向前跳,如上所述,

count = (count+y-1)%len(numbers_copy) # again -1 as we count from 0

数字长度需要再次计算,因为由于删除元素而可能会更改列表。

最新更新