python - 如何打乱用户输入选择的元素?
问题描述
我有两个数组
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 随机播放列表中的所有元素。
解决方案
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_1
和arr_2
。它不会返回新列表。
推荐阅读
- mysql - 为什么mysql不执行查询?
- python - 在 jupyter notebook 中添加命令行参数
- android - 使用 textswitcher 切换文本时删除边距
- spring-boot - 端点调用使用@Transational 注释的多个方法不起作用
- java - 几个小时不活动后打开应用程序时黑屏
- c++ - 可以调整这两种方法,让我只解析一次命令行吗?
- rvest - RVest 试图抓取日期时间字段
- javascript - 尽管发送了数据,但对 Express 应用程序的请求带有空正文,但仅在一条路线中
- c# - Outlook 渲染问题
- javascript - 如何使 JS for 循环异步