[英]Inconsistency between test and django: :int() argument must be a string but also TypeError: string indices must be integers
[英]class 'int' instead of type 'int': string indices must be integers
我有一個簡單的 Python 函數,我在其中交換字符串中的值。 我這樣做是通過生成一個偽隨機整數,然后將它與下一個索引或前一個索引交換以避免越界異常。
但是,我收到TypeError: string indices must be integers
。 當我添加一個打印語句來檢查由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
是一串字母、數字和符號。
您不能使用元組來索引列表。 使用兩個單獨的索引操作來交換兩個索引:
sequence[swap_index], sequence[next_index] = sequence[next_index], sequence[swap_index]
請注意,您的測試swap_index != sequence_len
永遠不會為真,因為secrets.randbelow()
已經保證您獲得介於 0 和低於參數值之間的值。 當swap_index
等於sequence_len - 1
,您將遇到索引錯誤,因為next_index
被設置為等於sequence_len
,這不是一個有效的索引。
接下來,如果sequence
是不可變類型,例如字符串,則無法分配給索引。 您必須首先將字符串轉換為可變序列,例如列表,然后再轉換回字符串(使用str.join()
)。
最后,您的實現僅直接交換連續的元素,這並不是真正的正確洗牌。 您需要考慮所有尚未交換的元素。
最后,要“安全地” secrets.SystemRandom()
序列,只需使用secrets.SystemRandom()
類並調用它的shuffle()
方法:
from secrets import SystemRandom
sysrandom = SystemRandom()
def shuffle_sequence(sequence):
sequence = list(sequence)
sysrandom.shuffle(sequence)
return ''.join(sequence)
該實施Random.shuffle()
越過序列的反向指標,並挑選出一個隨機元素謊言迭代索引之前:
for next_index in reversed(range(1, sequence_len)):
swap_index = random.randbelow(next_index)
sequence[swap_index], sequence[next_index] = sequence[next_index], sequence[swap_index]
這里有兩個問題:
您需要將字符串擴展為列表,在那里執行交換,然后將列表元素連接回字符串。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.