我有一个简单的Python函数,我在字符串中交换值。我这样做是通过生成一个伪随机整数,然后用下一个索引或上一个索引交换它来避免超出范围的异常。
但是,我正在获得TypeError: string indices must be integers
。当我添加一个print语句来检查由secrets.randbelow()
函数生成的索引的类型时,它返回class 'int'
,而我期望type 'int'
。这是导致错误的原因吗?
功能
import secrets as random
def shuffle_sequence(sequence):
sequence_len = int(len(sequence))
for x in range(0, sequence_len):
swap_index = random.randbelow(sequence_len)
next_index = 0
if swap_index != sequence_len:
next_index = swap_index + 1
else:
next_index = swap_index - 1
sequence[swap_index, next_index] = sequence[next_index, swap_index]
x += 1
return sequence
我甚至在函数的第一行添加了一个int转换,希望这会有所帮助,但它返回的是同一类int
,这是预期的。
为了澄清,sequence
是一串字母,数字和符号。
这里有两个问题:
您需要将字符串展开到列表,在那里执行交换,然后将列表元素连接回字符串。
def shuffle_sequence(sequence):
# "abc" -> ["a", "b", "c"]
elements = list(sequence)
sequence_len = int(len(sequence))
for x in range(0, sequence_len):
swap_index = random.randbelow(sequence_len)
next_index = 0
if swap_index != sequence_len:
next_index = swap_index + 1
else:
next_index = swap_index - 1
# Swap elements of the list
elements[swap_index], elements[next_index] = elements[next_index], elements[swap_index]
x += 1
# Combine the elements into a single string
return ''.join(elements)