如何将列表转换成字典对象?

时间:2019-01-19 00:55:08

标签: python-3.x list dictionary

我有一个看起来像这样的列表列表:

[[['1',
    '1@1`']],
  [['2', '2@2.com']],
  [['3', '3@3.com']],
  [['4', '4@4.com']],
  [['5', '5@5.com']],
  [['6', '6@6']],
  [['7', '7@7']],
  [['8', '8@8']],
  [['8.5', '8.5@8.5']],
  [['9', '9@9']],
  [['10', '10@10']],
  [['11', '11@11']],
  [['12', '12@12']],
  [['13', '13@13.com']],
  [['14', '14@14.com']],
  [['15', '15@15.com']],
  [['16', '16@16.com']],
  [['17', '17@17.com']],
  [['18@18.com', '18']],
  [['19', '19@19.com']]]

无论如何,我可以通过将其变成字典对象来清理列表,如下所示:

[{id:1,email:1@1},{id:2,email:2@2.com}]

理想情况下,在id位置是否有任何电子邮件被翻转到email位置?

1 个答案:

答案 0 :(得分:2)

您可以使用列表理解:

In [1]: mylist = [[['1',
   ...:     '1@1`']],
   ...:   [['2', '2@2.com']],
   ...:   [['3', '3@3.com']],
   ...:   [['4', '4@4.com']],
   ...:   [['5', '5@5.com']],
   ...:   [['6', '6@6']],
   ...:   [['7', '7@7']],
   ...:   [['8', '8@8']],
   ...:   [['8.5', '8.5@8.5']],
   ...:   [['9', '9@9']],
   ...:   [['10', '10@10']],
   ...:   [['11', '11@11']],
   ...:   [['12', '12@12']],
   ...:   [['13', '13@13.com']],
   ...:   [['14', '14@14.com']],
   ...:   [['15', '15@15.com']],
   ...:   [['16', '16@16.com']],
   ...:   [['17', '17@17.com']],
   ...:   [['18@18.com', '18']],
   ...:   [['19', '19@19.com']]]

In [2]: [{'id': i, 'email': e} for i, e in (pair[0] if '@' not in pair[0][0] else reversed(pair[0]) for pair in mylist)]
Out[2]:
[{'id': '1', 'email': '1@1`'},
 {'id': '2', 'email': '2@2.com'},
 {'id': '3', 'email': '3@3.com'},
 {'id': '4', 'email': '4@4.com'},
 {'id': '5', 'email': '5@5.com'},
 {'id': '6', 'email': '6@6'},
 {'id': '7', 'email': '7@7'},
 {'id': '8', 'email': '8@8'},
 {'id': '8.5', 'email': '8.5@8.5'},
 {'id': '9', 'email': '9@9'},
 {'id': '10', 'email': '10@10'},
 {'id': '11', 'email': '11@11'},
 {'id': '12', 'email': '12@12'},
 {'id': '13', 'email': '13@13.com'},
 {'id': '14', 'email': '14@14.com'},
 {'id': '15', 'email': '15@15.com'},
 {'id': '16', 'email': '16@16.com'},
 {'id': '17', 'email': '17@17.com'},
 {'id': '18', 'email': '18@18.com'},
 {'id': '19', 'email': '19@19.com'}]

如果您有任意嵌套,则可以尝试以下操作:

def flatten(lst):
    for sub in lst:
        if isinstance(sub, list):
            yield from flatten(sub)
        else:
            yield sub

[{'id': i, 'email': e} for i, e in (pair if '@' not in pair[0] else reversed(pair) for pair in zip(*[flatten(mylist)]*2))]