英文:
Randomly creating a sets of 2 numbers from a list that contains list of numbers
问题
所以我的问题是,我有一个包含多个列表的列表(就像一个分成较小子组的组,大小相同),我需要随机匹配两个数字并将它们设置为不重复的一对。匹配可以在同一子组内或来自其他子组,但最重要的是不能重复使用相同的数字。
首先,我使用NumPy对数字进行随机排列,然后使用reshape将其分成我想要的子组大小:
arr = np.random.permutation(40).reshape(10, 4) # 例如的数字
匹配的部分是我无法理解的部分,我尝试查找,但没有找到有助于我的情况的东西。
例如:
- 输入:
[[1,2,3],[4,5,6]]
- 期望输出:类似于
[(1,5),(2,3),(4,6)]
的随机对。
英文:
So the problem im having is that I have a list that contains multiple lists (like a group divided to smaller subgroups with even size) and I need to randomly match 2 numbers and make them a set without repetition. The matching can be within the same subgroup or from other subgroup but the most important part is that you cant use the same number more than once.
So at first I used NumPy for random permutation of the numbers and then reshape for dividing it to subgroups in the size I want:
arr = np.random.permutation(40).reshape(10, 4) #numers for example
The part of the matching is the part that I cannot understand, I tried to look it up but didnt found somthing that helped my situation.
Example:
- Input:
[[1,2,3],[4,5,6]]
- Expected output: random pairs like
[(1,5),(2,3),(4,6)]
答案1
得分: 2
一种方法是将列表展开,随机洗牌,然后分成所需大小的块:
arr = [[1,2,3], [4,5], [42,555, 777]]
flattened_list = [item for sublist in arr for item in sublist]
np.random.shuffle(flattened_list)
def chunk(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
result = list(chunk(flattened_list, 2))
print(result) # 示例输出 - [[555, 3], [2, 1], [42, 5], [777, 4]]
元组版本可以如下所示:
# ...
np.random.shuffle(flattened_list)
it = iter(flattened_list)
result = [*zip(it, it)]
英文:
One approach can be to flatten the list, shuffle it and then split into chunks of needed size:
arr = [[1,2,3], [4,5], [42,555, 777]]
flattened_list = [item for sublist in arr for item in sublist]
np.random.shuffle(flattened_list)
def chunk(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
result = list(chunk(flattened_list, 2))
print(result) # sample output - [[555, 3], [2, 1], [42, 5], [777, 4]]
Tuple version can look like the following:
# ...
np.random.shuffle(flattened_list)
it = iter(flattened_list)
result = [*zip(it, it)]
答案2
得分: 0
一个纯粹的Python解决方案(即没有使用Numpy)将是
```python
import random
l = [[1,2,3],[4,5,6]]
# 扁平化子列表
flat_l = [item for sublist in l for item in sublist]
# 在扁平化列表中洗牌元素(原地操作)
random.shuffle(flat_l)
# 通过配对洗牌列表的前半部分和后半部分的元素创建两元组
len_half = len(flat_l) // 2
result = [*zip(flat_l[:len_half], flat_l[len_half:])]
英文:
A pure Python solution (i.e. without Numpy) would be
import random
l = [[1,2,3],[4,5,6]]
# Flatten sublists
flat_l = [item for sublist in l for item in sublist]
# Shuffle elements in flattened list (in-place)
random.shuffle(flat_l)
# Create two-tuples by pairing elements in 1st and 2nd half of shuffled list
len_half = len(flat_l) // 2
result = [*zip(flat_l[:len_half], flat_l[len_half:])]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论