我的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 ?
答案 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]
给出A
。
lst[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
分配随机数。