我在python中有以下列表:
rooms = [1,'John','Mike','Simona',2,'Peter','Mark',3,'Olivia']
我想把它转换成字典。整数表示房间和名称是字符串:
rooms = {'room1': ['John','Mike','Simona'], 'room2': ['Peter','Mark'], 'room3': ['Olivia']}
我怎样才能以优雅的方式做到这一点?
答案 0 :(得分:5)
您可以使用itertools.groupby()
按类型分组:
from itertools import groupby
grouped = groupby(rooms, type)
rooms = {}
for key, grp in grouped:
roomname = 'room{}'.format(next(grp))
rooms[roomname] = list(next(grouped)[1])
这会按对象类型将输入列表分组。这为您提供了int
和str
值的交替组。然后循环检索奇数组(整数);循环体中的next(grouped)
调用检索偶数组。
这假设a)你的第一个值是房间号,b)房间号从不直接跟另一个整数。如果是,则完全忽略这些整数。
演示:
>>> from itertools import groupby
>>> rooms = [1,'John','Mike','Simona',2,'Peter','Mark',3,'Olivia']
>>> grouped = groupby(rooms, type)
>>> rooms = {}
>>> for key, grp in grouped:
... roomname = 'room{}'.format(next(grp))
... rooms[roomname] = list(next(grouped)[1])
...
>>> rooms
{'room2': ['Peter', 'Mark'], 'room3': ['Olivia'], 'room1': ['John', 'Mike', 'Simona']}
答案 1 :(得分:2)
以下内容对您有所帮助。
rooms = [1,'John','Mike','Simona',2,'Peter','Mark',3,'Olivia']
new_dict = {}
for value in rooms:
if isinstance(value, int):
ID = "room"+str(value)
else:
new_dict.setdefault(ID, []).append(value)
print new_dict
输出:
{'room1': ['John', 'Mike', 'Simona'], 'room2': ['Peter', 'Mark'], 'room3': ['Olivia']}