简体   繁体   English

Python 2D数组-通过键获取值

[英]Python 2D Array - Get Value by Key

Suppose it is the following structure given: 假设给出以下结构:

from django.utils.translation import ugettext_lazy as _

# Constants for all available difficulty types.
SIMPLE = 1
MEDIUM = 2
DIFFICULT = 3

# Names for all available difficulty types.
DIFFICULTIES = (
    (SIMPLE, _("simple")),
    (MEDIUM, _("medium")),
    (DIFFICULT, _("difficult")),
)

How do you get the string value, if a constant is given? 如果给定常量,如何获得字符串值?

A loop is easy to program, but is there a shorter python-like way with a single expression? 循环很容易编程,但是是否有一个带有单个表达式的类似python的较短方法?

The expression 表达方式

DIFFICULTIES[SIMPLE][1] 困难[简单] [1]

returns the string "medium". 返回字符串“ medium”。 What is obviously wrong. 显然有什么问题。

Of course you can use a dict, but the array is given. 当然,您可以使用字典,但是会给出数组。

So exchange it. 所以交换它。 (I'm assuming you kept the receipt..) (我假设您保留了收据。)

>>> dict(DIFFICULTIES)
{1: 'simple', 2: 'medium', 3: 'difficult'}
>>> d = dict(DIFFICULTIES)
>>> d[MEDIUM]
'medium'

Searching through an unsorted tuple for something simply isn't the right way to go about things. 在未排序的元组中搜索某些东西根本不是解决问题的正确方法。 I suppose you could do 我想你可以做

>>> next(v for k,v in DIFFICULTIES if k == MEDIUM)
'medium'

if you wanted to avoid a for loop with a colon, but that's a little silly. 如果您想避免带冒号的for循环,但这有点傻。

it just because you specified a tuple, an indexing starting from 0, you either need to switch to dictionary or modify your constants with correct values: 仅仅是因为您指定了一个元组(从0开始的索引),您要么需要切换到字典,要么用正确的值修改常量:

DIFFICULTIES = {SIMPLE: "simple", MEDIUM: "medium", DIFFICULT: "difficult"}

OR: 要么:

SIMPLE, MEDIUM, DIFFICULT = range(3)

Use a dictionary: 使用字典:

SIMPLE, MEDIUM, DIFFICULT = range(3)
DIFFICULTIES = {
    SIMPLE: _("simple"),
    MEDIUM: _("medium"),
    DIFFICULT: _("difficult")
}
DIFFICULTIES[SIMPLE] # will return "simple"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM