提取集合中的元组

发布于 2025-01-10 06:57:24 字数 580 浏览 0 评论 0原文

我有这个集合的样本: {(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2 , 1, 4), (2, 2, 3)}。

现在我需要删除包含一些特定数字的元组。例如:从该集合中删除包含 [4,5] 的元组,因此样本的输出应为:{(1, 3, 3), (2, 2, 3)}。

我用这段代码找到了所有组合,但我现在被困住了。

def compositions(k, n):
    if n==0:
        return []
    
    if k == 1:
        return [(n,)]

    comp = []
    for i in range(n + 1):
        for t in compositions(k - 1, n - i):
            if i>0:
                comp.append((i,) + t)
                
           
    return set(comp)
compositions(3, 7)

我该怎么做?

预先非常感谢您。

I have this sample of set: {(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2, 1, 4), (2, 2, 3)}.

Now i need to remove the tuples that contains some specific numbers. For example: From this set, remove the tuples that contain [4,5], so the output should be this: {(1, 3, 3), (2, 2, 3)} for the sample.

I used this code to find all combinations but i'm stucked now.

def compositions(k, n):
    if n==0:
        return []
    
    if k == 1:
        return [(n,)]

    comp = []
    for i in range(n + 1):
        for t in compositions(k - 1, n - i):
            if i>0:
                comp.append((i,) + t)
                
           
    return set(comp)
compositions(3, 7)

How can i do this?

Thank you very much in advance.

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

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

发布评论

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

评论(2

不如归去 2025-01-17 06:57:24

这可以通过一行代码来完成。

your_set = {(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2, 1, 4), (2, 2, 3)}
your_set = {ele for ele in your_set if all(x not in ele for x in [4, 5])}
print(your_set)

印刷:

{(2, 2, 3), (1, 3, 3)}

This can be accomplished with a one-liner.

your_set = {(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2, 1, 4), (2, 2, 3)}
your_set = {ele for ele in your_set if all(x not in ele for x in [4, 5])}
print(your_set)

Prints:

{(2, 2, 3), (1, 3, 3)}
冷…雨湿花 2025-01-17 06:57:24
def extract(array, filter):
    res = []
    for i in array:
        flag = 1
        for j in filter:
            if j in i:
                flag = 0
                break
        if flag:
            res.append(i)
    return res

print(
    extract(
        [(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2, 1, 4), (2, 2, 3)],
        [4,5]
        )
    )

你可以尝试这样的事情。

def extract(array, filter):
    res = []
    for i in array:
        flag = 1
        for j in filter:
            if j in i:
                flag = 0
                break
        if flag:
            res.append(i)
    return res

print(
    extract(
        [(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2, 1, 4), (2, 2, 3)],
        [4,5]
        )
    )

You can try something like this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文