【发布时间】:2017-03-11 14:39:45
【问题描述】:
给定
a = ['hello','world','1','2']
想要输出(特别是第一个元素从列表中生成键)
字典或元组
{'hello':['world','1','2']}
再想一想,您将如何概括这一点来选择任何作为键或值的项目,值?
【问题讨论】:
标签: python list dictionary
给定
a = ['hello','world','1','2']
想要输出(特别是第一个元素从列表中生成键)
字典或元组
{'hello':['world','1','2']}
再想一想,您将如何概括这一点来选择任何作为键或值的项目,值?
【问题讨论】:
标签: python list dictionary
你可以使用索引和切片
>>> 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']}
【讨论】: