Abstract:
conversion among list, dictionary.
1. Convert the
list to dictionary type using the function zip() and dict()
>>> a=range(10) #numeric
>>> d=dict(zip(a,a))
>>> print d
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
>>> a=['a','b','c'] #string type
>>> b=['a1','b1','c1']
>>> print zip(a,b)
[('a', 'a1'), ('b', 'b1'), ('c', 'c1')]
>>> print dict(zip(a,b))
{'a': 'a1', 'c': 'c1', 'b': 'b1'}
In the example, the
indexes and elements of the list are used as the keys and values of
the dictionary.
>>> a=['1','a12', 'b34']
>>> d={key:value for key, value in enumerate(a)}
>>> print d
{0: '1', 1: 'a12', 2: 'b34'}
2. Subset of a
list
>>>
a=range(10)
>>> a
[0, 1, 2, 3, 4, 5,
6, 7, 8, 9]
>>> a[:3]
#the first three elements
[0, 1, 2]
>>> a[:-3]
#remove the last three elements
[0, 1, 2, 3, 4, 5,
6]
>>> a[-3:]
#the last three elements
[7, 8, 9]
>>> a[2:5]
#Three continuous elements in the middle
[2, 3, 4]
writing date:
20150522
No comments:
Post a Comment