【问题标题】:How to select specific items in list to make dictionary keys and values如何选择列表中的特定项目以制作字典键和值
【发布时间】:2017-03-11 14:39:45
【问题描述】:

给定

a = ['hello','world','1','2']

想要输出(特别是第一个元素从列表中生成键)

字典或元组

{'hello':['world','1','2']}

再想一想,您将如何概括这一点来选择任何作为键或值的项目,值?

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    你可以使用索引和切片

    >>> a = ['hello','world','1','2']
    >>> {a[0]: a[1:]}
    {'hello': ['world', '1', '2']}
    

    选择任何索引作为键,并将所有剩余项作为值

    def make_dict(items, index):
        return {items[index]: items[:index] + items[index+1:]}
    

    例如

    >>> a = ['hello','world','1','2']
    >>> make_dict(a, 0)
    {'hello': ['world', '1', '2']}
    >>> make_dict(a, 1)
    {'world': ['hello', '1', '2']}
    >>> make_dict(a, 2)
    {'1': ['hello', 'world', '2']}
    >>> make_dict(a, 3)
    {'2': ['hello', 'world', '1']}
    

    【讨论】:

    • 不知道为什么有人投了反对票,这回答了 OPs 的问题。投票平衡。
    猜你喜欢
    • 2016-01-02
    • 1970-01-01
    • 2013-07-09
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多