Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

You could use an iter of the list to get the next element, and then the next two after that:

>>> 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; (b) this will fail if the number of elements is not divisible by three.

As noted in comments, this only works properly a reasonably new version of Python. Alternatively, you can use a range with step and the index:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...