【问题标题】:How do I create x amount of lists/sets that i can later add together?如何创建 x 数量的列表/集合,以便以后添加?
【发布时间】:2019-10-20 02:33:19
【问题描述】:

我正在做一个项目,我必须检查某些东西是否在另一个集合中,如果是,那么我必须合并这些集合。

我的问题是如何创建 x 数量的集合,其中包含 y 数量的值。

我想随机化这种数据 有 x 组在 y1 和 y2 之间的“名称” 示例:

    x=5
    y1=2
    y2=4
    ["1","2","3"]
    ["6","1","2"]
    ["9","7","4","0"]
    ["6","8","1"]
    ["1","5"]

有 5 组集合,其中包含 2 到 4 个“名称”

如果一个值在多个集合中,我需要能够将这两个集合放在一起,在这种情况下,完成后它看起来像这样:

    ["1","2","3","6","8","5"]
    ["9","7","4","0"]

【问题讨论】:

  • 到目前为止您尝试过什么?你有没有想出一些代码?您现在的问题在哪里?

标签: python list loops random set


【解决方案1】:

这里有一些代码可以大致完成您想要的操作。查看 setsrandom numbers 上的文档,以更全面地了解此处发生的情况。

import random

# make a single set of random numbers in [0, 10), with number of elements in [y1, y2]
random_set = set(random.sample(range(10), random.randint(y1, y2)))

# make x sets of them
random_sets = [set(random.sample(range(10), random.randint(y1, y2))) for _ in range(x)]

# merge sets containing a given element
def merge_sets(list_of_sets, elem):
    # create an empty set
    elem_set = set()
    for s in list_of_sets:
        # go through all the sets in the list, and if those sets contain the 
        # element we're looking for, merge them into the new set
        if elem in s:
            elem_set |= s
    # return the list of new set plus those sets that didn't contain our element
    return [elem_set] + [s for s in list_of_sets if elem not in s]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    相关资源
    最近更新 更多