简体   繁体   English

以元组为键将列表转换为字典

[英]Transform a list to dict with tuple as key

I want to do from list ['sw0005', 'sw0076', 'Gi1/2', 'sw0005', 'sw0076', 'Gi1/5'] Dict with tuple, which will looks like {('sw0005','sw0076'):'Gi1/2', ('sw0005','sw0076'):'Gi1/5'} How's better it can be done in python?我想从列表中做['sw0005', 'sw0076', 'Gi1/2', 'sw0005', 'sw0076', 'Gi1/5']带有元组的字典,看起来像{('sw0005','sw0076'):'Gi1/2', ('sw0005','sw0076'):'Gi1/5'}如何在 python 中做得更好?

You could use an iter of the list to get the next element, and then the next two after that:您可以使用列表的一个iter器来获取下一个元素,然后是next的两个:

>>> lst = ['sw0005', 'sw0076', 'Gi1/2', 'sw0006', 'sw0076', 'Gi1/5']        
>>> it = iter(lst)                                                          
>>> {(a, next(it)): next(it) for a in it}                                   
{('sw0005', 'sw0076'): 'Gi1/2', ('sw0006', 'sw0076'): 'Gi1/5'}

Note: (a) I changes the list so the two tuples are not the same;注意:(a)我更改了列表,因此两个元组不相同; (b) this will fail if the number of elements is not divisible by three. (b) 如果元素的数量不能被三整除,这将失败。

As noted in comments, this only works properly a reasonably new version of Python.如评论中所述,这只适用于相当新的 Python 版本。 Alternatively, you can use a range with step and the index:或者,您可以使用带step和索引的range

>>> {(lst[i], lst[i+1]): lst[i+2] for i in range(0, len(lst), 3)}
{('sw0005', 'sw0076'): 'Gi1/2', ('sw0006', 'sw0076'): 'Gi1/5'}

I made the iterable more readable我使可迭代的内容更具可读性

 list1=['sw0005', 'sw0076', 'Gi1/2', 'sw0005', 'sw0076', 'Gi1/5']

 queryable=iter(list1)

 mylist=[]
 for i in range(int(len(list1)/3)):
     mylist.append({(next(queryable),next(queryable)):next(queryable)})

 print(mylist)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM