首页 > 解决方案 > 如何打乱用户输入选择的元素?

问题描述

我有两个数组

arr_1 = [2, 4, 6, 32] 
arr_2 = [56, 45, 12, 65]

我想从“arr_1 列表”中提供 user_input

例如,如果我选择从 'arr_1 list' 给 user_input '32',它应该将 '32' 洗牌到 'arr_1 list' 中的任何位置,并且与 '32' 一起来自 'arr_2 list' 的元素在相同的位置'65' 也应该是洗牌。我尝试了很多方法,但它使用 random.shuffle 随机播放列表中的所有元素。

标签: python

解决方案


from random import randint

def shuffle_them(arr_1, arr_2, element_to_remove):
    # get the index where to be removed element is
    index_to_remove = arr_1.index(element_to_remove)

    # remove that element
    arr_1.remove(element_to_remove)
    
    # randomly generate the new index
    new_index = randint(0, len(arr_1))

    # insert the removed element into that position in array 1
    arr_1.insert(new_index, element_to_remove)

    # also change the position of elements in array 2 accordingly
    arr_2[new_index], arr_2[index_to_remove] = arr_2[index_to_remove], arr_2[new_index]

我们找到用户想要移动的元素的索引。然后我们删除它。然后我们为其生成一个新索引并将其插入其中。最后,我们使用原始索引和新索引来交换第二个数组中的值。

用法

# before
arr_1 = [2, 4, 6, 32]
arr_2 = [56, 45, 12, 65]

# shuffiling
shuffle_them(arr_1, arr_2, element_to_remove=32)

# after (32 and 65 places changed in same way)
> arr_1
[2, 32, 4, 6]

> arr_2
[56, 65, 12, 45]

再来一轮

# before
arr_1 = [2, 4, 6, 32]
arr_2 = [56, 45, 12, 65]

# shuffiling
shuffle_them(arr_1, arr_2, element_to_remove=6)

# after (6 and 12 places changed in same way)
> arr_1
[2, 4, 32, 6]

> arr_2
[56, 45, 65, 12]

注意:函数直接改变可变的arr_1arr_2。它不会返回新列表。


推荐阅读