字典交集后去掉括号

发布于 2024-12-27 05:39:12 字数 501 浏览 4 评论 0原文

我正在研究一个问题,并得到了一个非常接近的答案......基本上,问题是你有两个字典,你必须找到与两个字典相交的元素,然后创建这些元素(两个字典中的一个相同的键)以及来自两个 dic 的两个值)在新字典中。

a = {'A':17,'B':31,'C':42,'D':7,'E':46,'F':39,'G':9}
b = {'D':8,'E':3,'F':2,'g':5}

def intersect(a,b):
    c = set(a).intersection(set(b))
    d = {}
    for i in c:
        if i in a:
            d[i] = int(a[i]),int(b[i])
    return d

OUTPUT: {'E': (46, 3), 'D': (7, 8), 'F': (39, 2)}

我想要得到类似 {'E': 46, 3, 'D': 7, 8, 'F': 39, 2} 的输出

如何去掉值周围的括号?

There is one question I am working on and got a very close answer... basically, the question is that you get two dictionaries and you have to find elements that intersect from both dictionaries and then create those elements (one same key from both dicts and two values from both dics) in a new dictionary.

a = {'A':17,'B':31,'C':42,'D':7,'E':46,'F':39,'G':9}
b = {'D':8,'E':3,'F':2,'g':5}

def intersect(a,b):
    c = set(a).intersection(set(b))
    d = {}
    for i in c:
        if i in a:
            d[i] = int(a[i]),int(b[i])
    return d

OUTPUT: {'E': (46, 3), 'D': (7, 8), 'F': (39, 2)}

I want to get the output like {'E': 46, 3, 'D': 7, 8, 'F': 39, 2}

How do I get rid of the parentheses around the values?

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

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

发布评论

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

评论(2

奢望 2025-01-03 05:39:12

您编写的代码根本不会输出任何内容。但是,如果您想删除括号,则可以使用它。

str(intersect(a, b)).replace('(', '').replace(')', '')

或者等效于此,这更简洁和高效

str(intersect(a, b)).translate(None, '()')

The code as you have written won't output anything at all. However, if you want to remove parentheses, then you can use this.

str(intersect(a, b)).replace('(', '').replace(')', '')

or equivalently this, which is a bit more concise and efficient

str(intersect(a, b)).translate(None, '()')
玩套路吗 2025-01-03 05:39:12

您看到的输出是字典的 Python 表示形式。您所构建的(据我所知,您已经正确构建了它 - 这就是您想要的)是将键映射到项目对的字典。这些对是元组,并且在它们周围打印有括号。

听起来您想要的是一种获取字典并打印它并以特定方式格式化的方法。

像这样的东西会按照你想要的方式打印字典:

def dictionary_printer(d):
    print "{%s}" % ', '.join(
        [("'%s': %s" % (key, ', '.join(map(str,value))))
        for key, value in d.items()]
    )

The output you are seeing is the python representation of your dictionary. What you have built (and, as far as I can tell, you have built it correctly -- it's what you want) is a dictionary mapping keys to pairs of items. The pairs are tuples, and those get printed with parentheses around them.

It sounds like what you want is an method which takes your dictionary and prints it, formatted in a specific way.

Something like this would print the dictionary the way you want it to:

def dictionary_printer(d):
    print "{%s}" % ', '.join(
        [("'%s': %s" % (key, ', '.join(map(str,value))))
        for key, value in d.items()]
    )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文