如何将列表随机划分为n个几乎相等的部分?

发布于 2024-09-11 23:25:54 字数 524 浏览 8 评论 0原文

我已阅读 将列表切成 n 的答案 -等长分区[重复]问题。

这是接受的答案

def partition(lst, n): 
    division = len(lst) / float(n) 
    return [ lst[int(round(division * i)): int(round(division * (i + 1)))] for i in xrange(n) ]

我想知道如何修改这些解决方案,以便将项目随机分配到分区而不是增量分配。

I have read the answers to the Slicing a list into n nearly-equal-length partitions [duplicate] question.

This is the accepted answer:

def partition(lst, n): 
    division = len(lst) / float(n) 
    return [ lst[int(round(division * i)): int(round(division * (i + 1)))] for i in xrange(n) ]

I am wondering, how does one modify these solutions in order to randomly assign items to a partition as opposed to incremental assignment.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

寄人书 2024-09-18 23:25:54

调用 random.shuffle()分区之前列出。

Call random.shuffle() on the list before partitioning it.

遗弃M 2024-09-18 23:25:54

完整的 2018 年解决方案(python 3.6):

import random 
def partition (list_in, n):
    random.shuffle(list_in)
    return [list_in[i::n] for i in range(n)]

小心!这可能会改变您的原始列表

Complete 2018 solution (python 3.6):

import random 
def partition (list_in, n):
    random.shuffle(list_in)
    return [list_in[i::n] for i in range(n)]

Beware! this may mutate your original list

鹿港巷口少年归 2024-09-18 23:25:54

随机播放输入列表。

shuffle input list.

情徒 2024-09-18 23:25:54

首先,将列表随机化,然后将其分成几乎相等的 n 个部分。

First you randomize the list and then you split it in n nearly equal parts.

仅一夜美梦 2024-09-18 23:25:54

打乱列表并不能保持顺序。你可以做这样的事情(很容易适应两个以上的部分)。完全未经测试。

from __future__ import annotations
from typing import TypeVar
import random

T = TypeVar("T")

def partition_list(s: list[T]) -> tuple[list[T], list[T]]:
    """
    Randomly partition a list into two lists, preserving order. The number to
    take is drawn from a uniform distribution.
    """
    len_a = random.randint(0, len(s))
    len_b = len(s) - len_a
    put_in_a = [True] * len_a + [False] * len_b
    random.shuffle(put_in_a)
    a: list[T] = []
    b: list[T] = []

    for val, in_a in zip(s, put_in_a):
        if in_a:
            a.append(val)
        else:
            b.append(val)

    return a, b

Shuffling the list doesn't preserve order. You could do something like this instead (pretty easy to adapt to more than two parts). Completely untested.

from __future__ import annotations
from typing import TypeVar
import random

T = TypeVar("T")

def partition_list(s: list[T]) -> tuple[list[T], list[T]]:
    """
    Randomly partition a list into two lists, preserving order. The number to
    take is drawn from a uniform distribution.
    """
    len_a = random.randint(0, len(s))
    len_b = len(s) - len_a
    put_in_a = [True] * len_a + [False] * len_b
    random.shuffle(put_in_a)
    a: list[T] = []
    b: list[T] = []

    for val, in_a in zip(s, put_in_a):
        if in_a:
            a.append(val)
        else:
            b.append(val)

    return a, b
苍风燃霜 2024-09-18 23:25:54

随机分区也保留顺序:(

def partition_preserve_order(list_in, n):
    indices = list(range(len(list_in)))
    shuffle(indices)
    index_partitions = [sorted(indices[i::n]) for i in range(n)]
    return [[list_in[i] for i in index_partition] 
            for index_partition in index_partitions]

也就是说,我们对索引进行洗牌,然后在分区内对它们进行排序)

示例:

random_partition_preserve_order(list('abcdefghijklmnopqrstuvxyz'), 3)
# [
#     ['c', 'd', 'g', 'm', 'p', 'r', 'v', 'x', 'y'], 
#     ['b', 'e', 'h', 'k', 'o', 'q', 't', 'u'], 
#     ['a', 'f', 'i', 'j', 'l', 'n', 's', 'z']
# ]

The random partition that also preserves the order:

def partition_preserve_order(list_in, n):
    indices = list(range(len(list_in)))
    shuffle(indices)
    index_partitions = [sorted(indices[i::n]) for i in range(n)]
    return [[list_in[i] for i in index_partition] 
            for index_partition in index_partitions]

(that is we shuffle the indices then sort them within the partitions)

example:

random_partition_preserve_order(list('abcdefghijklmnopqrstuvxyz'), 3)
# [
#     ['c', 'd', 'g', 'm', 'p', 'r', 'v', 'x', 'y'], 
#     ['b', 'e', 'h', 'k', 'o', 'q', 't', 'u'], 
#     ['a', 'f', 'i', 'j', 'l', 'n', 's', 'z']
# ]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文