列表可以
mylist = ['a',1,2,'b',3,4,'c',5,6]
用于创建字典
mydict = {'a':(1,2),'b':(3,4),'c':(5,6)}
答案 0 :(得分:3)
您可以尝试这样的事情:
>>> mylist = ['a',1,2,'b',3,4,'c',5,6]
>>>
>>> v = iter(mylist)
>>> mydict = {s: (next(v),next(v)) for s in v}
>>> mydict
{'a': (1, 2), 'c': (5, 6), 'b': (3, 4)}
答案 1 :(得分:1)
只有你有某种标准才是关键。如果字符串是键,那么:
d = {}
key = None
for item in my_list:
if isinstance(item, str):
key = item
else:
d.setdefault(key, []).append(item)
答案 2 :(得分:0)
>>> dict((x, (y, z)) for (x, y, z) in zip(*[iter(['a',1,2,'b',3,4,'c',5,6])]*3))
{'a': (1, 2), 'c': (5, 6), 'b': (3, 4)}
答案 3 :(得分:0)
mylist = ['a',1,2,'b',3,4,'c',5,6]
mydict = {}
for i in range(len(mylist))[::3]:
mydict[mylist[i]] = (mylist[i+1],mylist[i+2])
答案 4 :(得分:0)
是的,但您的mydict应该使用围绕字符串的引号和列表周围的方括号创建:
mydict = {"a":[1,2],"b":[3,4],"c":[5,6]}
否则,如果您希望使用该列表以编程方式创建字典:
mydict = {}
i = 0
while i < len(mylist):
mydict[mylist[i]] = [mylist[i+1], mylist[i+2]]
i = i + 3