您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

创建一个可以将列表转换为python字典的函数

创建一个可以将列表转换为python字典的函数

将 列表传递给 构造函数enumerateddict

>>> items = ['a','b','c']
>>> dict(enumerate(items, 1))
>>> {1: 'a', 2: 'b', 3: 'c'}

这里enumerate(items, 1)将产生tuples的元素及其索引。 索引将从1(请注意的第二个参数enumerate)开始。 使用此表达式,您可以定义一个函数内联,例如:

>>> func = lambda x: dict(enumerate(x, 1))

像这样调用它:

>>> func(items)
>>> {1: 'a', 2: 'b', 3: 'c'}

或常规功能

>>> def create_dict(items):
        return dict(enumerate(items, 1))
python 2022/1/1 18:28:18 有222人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶