如何在Python中重新启动列表的迭代

时间:2018-04-04 14:03:27

标签: python list

我的Python程序有问题,我无法找到问题的答案。假设我有一个包含字母表中所有字符的列表,这意味着从A到Z。

list = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]

我想要一个列表的随机字符表单。让我们假设Z.现在我想迭代该列表13次。让我解释一下:如果我在Z上,Z + 13必须 M ,因为我会做A,B,C,D,E,F,G,H,I,J ,K,L,M。如果我会在A上并且我想要使用25例如它会很容易,因为它将是Z的最终结果。但是如果我放了一个27(所以它超过列表中的最大项目数),我怎样才能在25之后重新启动列表,以便A + 27 B

4 个答案:

答案 0 :(得分:1)

我认为您可以通过list[index % len(list)]

访问列表元素

答案 1 :(得分:1)

具有值为34的预定义索引的小例子:

l = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
index=34
print(l[index%len(l)]) # result 'I'

答案 2 :(得分:1)

要解决您的问题,您可以使用% len(lst)

lst = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
print(lst[0])  # A
print(lst[(0+27) % len(lst)])  # B

<强>解释

lst[0]给出Alst[0+27]不存在(lst的长度为26)。在那里你应该使用%运算符,它遵循lst的循环路径。

27 % 26 = 1 

因此,当您执行lst[1]时,实际上会致电lst[(0+27) % len(lst)]

注意: 请勿使用list作为变量名称。它会隐藏内置的list。尝试lst或其他。

答案 3 :(得分:1)

你可以这样做:

l = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
n = 13 # Chosen number (you can assign any integer you want)
r = 25 # Index of Z
element = l[(r + n) % len(l)]
print("Element: ", element)

输出:

Element:  M

您可以使用randint模块中的random功能为r以及n分配随机数。