将一维列表解析为字典

0 投票
2 回答
630 浏览
提问于 2025-04-17 07:40

我需要把下面这种列表格式转换成字典。

这个列表代表了2个人,每个人有3个数据,分别是名字、姓氏和电子邮件。

data = [3, 'firstname', 'lastname', 'email', 2, 'jack', 'black', 'jb@example.com', 'jane', 'green', 'jg@examlpe.com']

data[0] 表示发送了多少个人的信息。(3)

接下来的3个项目是这些数据的名称。

在实际的个人数据开始之前,数字2表示接下来有多少个人的信息。

我刚学Python,想知道有没有更简单的方法来处理这个。我觉得应该有更好的办法。

(这段代码没有测试,只是展示了我能想到的唯一方法)

def formatPeople(self, data):
  param_count = data[0]
  keys = []
  pos = 1
  while pos <= param_count:
    keys.append(data[pos])
    pos += 1;

  people_count = int(data[pos])
  pos += 1
  people = []

  i = 0
  while i < people_count:
    people_data = {}
    for x in keys:
        people_data[keys[x]] = data[pos]
        pos += 1

    people.append(people_data)
  return people

2 个回答

0

这段话是在说,使用列表推导式来完成这个工作非常合适。而且它只需要一行代码就能搞定,挺简洁的。 :)

people = [{data[j]: data[data[0] * (i + 1) + j + 1] for j in xrange(1, data[0] + 1)} for i in xrange(0, data[data[0] + 1])]
3

这是一个使用迭代器的好列表:

>>> i = iter(data)
>>> attr = [next(i) for x in range(next(i))]
>>> [{x:next(i) for x in attr} for y in range(next(i))]
[{'lastname': 'black', 'email': 'jb@example.com', 'firstname': 'jack'}, {'lastname': 'green', 'email': 'jg@examlpe.com', 'firstname': 'jane'}]

撰写回答