可以列出来
mylist = ['a',1,2,'b',3,4,'c',5,6]
用于创建字典
mydict = {'a':(1,2),'b':(3,4),'c':(5,6)}
你可以尝试这样的事情:
>>> 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)}
仅当您有某种标准时,哪些标准才是关键。如果字符串是键,那么:
d = {}
key = None
for item in my_list:
if isinstance(item, str):
key = item
else:
d.setdefault(key, []).append(item)
是的,但是您的 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
>>> 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)}
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])