我正在尝试使用scramble
函数对数组进行随机重排:
def scramble(arr):
arr_len = len(arr)
container = [None]*arr_len
indexes = [i for i in range(arr_len)]
print(random.choice(indexes)) # works as expected
for i in range(arr_len):
my_choice = None
while not my_choice:
my_choice = random.choice(indexes)
print(my_choice) # always None
if my_choice is not None:
indexes[my_choice] = None
container[my_choice] = arr[my_choice]
print(container)
scramble([2,3,4,5,6])
我面临的问题是my_choice
变量始终包含None
。有人可以指出我所缺少的吗?
答案 0 :(得分:2)
上述代码的问题在while not my_choice:
行中。请记住,my_choice
变量可以同时包含0和None
(这两个值都是虚假的)。
因此,我建议将您的代码更改为以下内容(如果您不想使用random.shuffle
):
def scramble(arr):
arr_len = len(arr)
container = [None]*arr_len
indexes = [i for i in range(arr_len)]
# print(random.choice(indexes)) # works as expected
for i in range(arr_len):
# print("i is {}".format(i))
my_choice = None
# while not my_choice:
while my_choice is None:
my_choice = random.choice(indexes)
print(my_choice) # always None
if my_choice is not None:
indexes[my_choice] = None
container[i] = arr[my_choice]
print(container)
scramble([2,3,4,5,6])
也请执行container[i] = arr[my_choice]
而不是container[my_choice] = arr[my_choice]
答案 1 :(得分:0)
发生此问题是因为您将indexes[my_choice]
设置为None,结果在某些时候indexes
列表中的所有元素都是None
,而while循环永无休止。 / p>
要对列表进行加扰,可以使用标准库中的random.shuffle函数:
import random
arr = [2,3,4,5,6]
random.shuffle(arr)
print arr