我有一个这样的列表:
['1',"Santa's little helper",'4','Team','6','Approximately 28.35 grams','7','Breakfast that can be "everything"','8','Was in first place']
如何使用如下理解方法将其转换为字典:
{'1': "Santa's little helper",'4': 'Team',........}
我有一个这样的列表:
['1',"Santa's little helper",'4','Team','6','Approximately 28.35 grams','7','Breakfast that can be "everything"','8','Was in first place']
如何使用如下理解方法将其转换为字典:
{'1': "Santa's little helper",'4': 'Team',........}
您可以使用itertools.zip_longest()
:
d = dict(itertools.zip_longest(l[::2],l[1::2],fillvalue=''))
我认为您不能使用dict理解来做到这一点,因为dict理解会涉及所有要素。您可以将列表一分为二,然后像这样进行dict理解
my_dict = {x: y for x in my_list for y in my_list2}
但是我认为这比付出更多的努力。
编辑:作为@pault注释,理解
{k: v for k,v in zip(myList[::2],myList[1::2])}
也可以。
,您可以使用列表理解遍历列表以生成元组对(i,i + 1)的列表。然后可以通过调用l
将它们转换为字典。
示例:
v = arrayfun(@(r) yuk_pot(r,l),r);