【问题标题】:Python Dictionary with Tuple as Values. Access the last index of the tuple以元组为值的 Python 字典。访问元组的最后一个索引
【发布时间】:2015-12-01 23:10:52
【问题描述】:

假设我有一本看起来像这样的字典: (所有元组的长度相同)

dict_new = {1:(1,2,"work"), 2:(3,4,"sleep")}

如何访问 key key 1 的最后一个索引(在本例中是它的“工作”):

【问题讨论】:

  • dict_new[1][-1] 将为您提供带有键 1 的值,然后在索引 -1 处为您获取项目,这是最后一个索引

标签: list python-3.x dictionary indexing tuples


【解决方案1】:

假设总是三项,可以直接通过索引引用:

dict_new[1][2]

如果您想要最后一个而不考虑元组长度,请使用负索引:

dict_new[1][-1]

但是,您的元组看起来像是某种数据容器;我强烈建议为此创建一个namedtuple 类,例如:

from collections import namedtuple

# define your data type and the fields it contains:
Entry = namedtuple('Entry', ['start', 'end', 'activity'])

# now add Entry objects instead of bare tuples:
dict_new = {1: Entry(1, 2, "work"), 2: Entry(3, 4, "sleep")}

然后您可以通过以下方式访问它:

dict_new[1].activity  # gives you "work"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2021-03-26
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2021-05-15
    相关资源
    最近更新 更多