Python中字典中键的多个值 [英] Multiple values for key in dictionary in Python

查看:75
本文介绍了Python中字典中键的多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是从一个键中获取3个值到单独的变量中.目前,我正在这样做:

What I'm trying to do is get 3 values from a key into separate variables. Currently I'm doing it like this:

for key in names:
   posX = names[key][0]
   posY = names[key][1]
   posZ = names[key][2]

对我来说,这似乎不是很直观,即使它可以工作.我也尝试过这样做:

This doesn't seem very intuitive to me even though it works. I've also tried doing this:

for key, value in names:
   location = value

不幸的是,这给了我一个对象(这是我所期望的),但是我需要为键分配单独的值.感谢并为我对Python的新颖性表示歉意.

Unfortunately, this gives me a single object (which is what I expected), but I need the individual values assigned to the key. Thanks and apologize for my newness to Python.

更新对于未指定我从何处获得价值的歉意.这是我在第一个示例中的做法.

Update Apologies for not specifying where I was getting my values from. Here is how I'm doing it for the first example.

names = {}

for name in objectNames:
    cmds.select(name)
    location = cmds.xform(q=True, ws=True, t=True)
    names[name] = location

推荐答案

这并非直觉.

在字典中存储给定键的多个值"的唯一方法是将某种容器对象存储为值,例如列表或元组.您可以通过对列表或元组进行下标来访问它,就像在第一个示例中一样.

The only way to store "multiple values" for a given key in a dictionary is to store some sort of container object as the value, such as a list or tuple. You can access a list or tuple by subscripting it, as you do in your first example.

您的示例的唯一问题是,以这种方式使用它是访问此类容器的丑陋且不便的方法.像这样尝试,您可能会更快乐:

The only problem with your example is that it's the ugly and inconvenient way to access such a container when it's being used in this way. Try it like this, and you'll probably be much happier:

>>> alist = [1, 2, 3]
>>> one, two, three = alist
>>> one
1
>>> two
2
>>> three
3
>>> 

因此,您的第二个示例可能是:

Thus your second example could instead be:

for key, value in names.items():
    posX, posY, posZ = value

正如FabienAndre在下面的评论中指出的那样,还有一个我完全忘记的更便捷的语法,即name.items()中的 key(posX,posY,posZ):.

As FabienAndre points out in a comment below, there's also the more convenient syntax I'd entirely forgotten about, for key,(posX,posY,posZ) in names.items():.

您没有指定从何处获取这些值,但是如果它们来自您可以控制的代码,并且您可以依赖使用Python 2.6或更高版本,则还可以考虑使用命名元组.然后,您可以提供一个命名的元组作为dict值,并使用语法 pos.x pos.y 等来访问这些值:

You don't specify where you're getting these values from, but if they're coming from code you have control over, and you can depend on using Python 2.6 or later, you might also look into named tuples. Then you could provide a named tuple as the dict value, and use the syntax pos.x, pos.y, etc. to access the values:

for name, pos in names.items():
    doSomethingWith(pos.x)
    doSomethingElseWith(pos.x, pos.y, pos.z)

这篇关于Python中字典中键的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆