本站消息

站长简介


前每日优鲜python全栈开发工程师,自媒体达人,逗比程序猿,钱少话少特宅,我的公众号:想吃麻辣香锅

  python大神匠心打造,零基础python开发工程师视频教程全套,基础+进阶+项目实战,包含课件和源码

  出租广告位,需要合作请联系站长



+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

如何从两个有序字典组合中提取单个值?

发布于2021-05-29 21:54     阅读(1103)     评论(0)     点赞(0)     收藏(2)


0

1

2

3

4

5

6



我试图返回两个有序字典,返回语句如下:

return self.objects, self.disappeared

它们被初始化为:

self.objects = OrderedDict()
self.disappeared = OrderedDict()

返回后,组合版本打印为:

(OrderedDict([(0, array([260, 181]))]), OrderedDict([(0, 0)]))

我目前将其提取为:

for (objectID, centroid) in objects.items():

但是,只有当我只返回self.objectsself.disappeared而不返回两者时,才有可能

我如何能够使用两个返回的字典提取值?


解决方案


看来您的问题在于处理返回的元组。https://www.geeksforgeeks.org/g-fact-41-multiple-return-values-in-python/查看“ 2)使用元组

这是使用您提供的部分的示例代码片段。

from typing import OrderedDict

class Thing:
    def __init__(self):
        # "They are initialized as: "
        self.objects = OrderedDict(objectID=1, centroid=[2,3])
        self.disappeared = OrderedDict(unknown=(4,5))

    def do_thing(self):
        # "I am trying to return two Ordered Dictionaries, the return statement is as follow: "
        return self.objects, self.disappeared

# "After returning, the combined version was printed out as: "
results = Thing().do_thing()
print(results)

# "How would I be able to extract values with two returning Dictionaries? "
objects, disappeared = results

for (objectID, centroid) in objects.items():
    print(f'{objectID}, {centroid}')

for item in disappeared.items():
    print(item)

do_thing()我们返回一个元组(self.objects, self.disappeared)

我们可以像这样解包这个元组(提取每个项目):

objects, disappeared = results

有关解包元组的更多信息:https : //www.geeksforgeeks.org/unpacking-a-tuple-in-python/

然后您将能够使用所写的代码:

for (objectID, centroid) in objects.items():
    print(f'{objectID}, {centroid}')



0

1

2

3

4



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/978282/26a55ba759001229b603/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

0 0
收藏该文
已收藏

评论内容:(最多支持255个字符)