列表索引 - 如果太大则返回列表的开头

时间:2018-04-25 18:06:45

标签: python list for-loop indexing

所以,也许这个问题听起来很初学,但我不知道如何从这个例子开始:

所以这个例子是: 我有一个列表,例如13项长(1,2,3,4 ... 13) 有一个给定的数字,让我们说6

该程序需要在列表中显示,数字将以什么顺序排除。如果第二个数字是6,则表示每次第六个项目是下一个数字将会失效。但我的问题是,我怎么能告诉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 = 13 y = 6

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

1 个答案:

答案 0 :(得分:2)

好的,看起来你想要将每个第6个元素从数字复制到fallout中,然后从数字中删除元素,然后以循环方式继续,直到数字为空。

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]

<强>解释

假设我有一个长度= 6的数组编号= [1,2,3,4,5,6],并且我使用计数器“count”来遍历列表。那就是,

  

number [count] = 2(当count = 1时)

然后看下一个元素,我会使用数字[count + 1]。 要跳回列表的开头,我们使用模运算,

  

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

例如,在index = 4并且跳跃3步,下一个索引将是(4 + 3)%6 = 1 现在我们必须复制列表中的每个第y个元素,所以我们使用

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

由于删除元素,列表可能会发生变化,因此需要再次计算数字的长度。