小编use*_*318的帖子

Python将排序后的List转换为Dict,其位置指定为(键,值)对

刚接触Python,转换排序列表的最佳方法是什么(是的,列表中的元素是唯一的):

[a0, a1, a2, a3, ..., aj, ... ]
Run Code Online (Sandbox Code Playgroud)

到Dict数据类型,其位置如下所示:

{
    a0: {'index':0},
    a1: {'index':1},
    a2: {'index':2},
    ...
    aj: {'index':j},
    ...
}
Run Code Online (Sandbox Code Playgroud)

请在此澄清一些问题:

  • 在dict中实际上有更多的对{'index': j, 'name': wow, ...}并且从列表转换为这样的dict是必要的,其他属性,比如'name'将在dict创建之后添加,所以基本上它看起来像下面,首先创建dict,然后第二个在aj添加其他属性的键上,其他属性稍后出现;
  • 明确定义index是必要的,它最终将如下所示:{'index': myFunc(j)}.

非常感谢您的帮助!


我尝试过的:

  1. 尝试l = zip(mylist, range(len(mylist)))并转换l(看起来像[(a0, 0), (a1, 1), ...])dict,然而,它是tuple内部的列表;
  2. 尝试d = dict(zip(mylist, range(mylist.len)))但仍然需要转换{ai: i}{ai:{'index': i}}并且不知道从这里解决的好方法;
  3. 尝试过天真的for循环,但不会发生

python dictionary data-structures

0
推荐指数
1
解决办法
1075
查看次数

标签 统计

data-structures ×1

dictionary ×1

python ×1