The realization method of sequence traversal and Dictionary traversal of python
This article mainly introduces "python sequence traversal and dictionary traversal implementation method", in daily operation, I believe many people in python sequence traversal and dictionary traversal implementation method problems have doubts, Xiaobian consulted all kinds of information, sorted out simple and easy to use operation method, hope to answer "python sequence traversal and dictionary traversal implementation method" doubts helpful! Next, please follow the small series to learn together!
There are six built-in sequences in Python: lists, tuples, strings, Unicode strings, buffer objects, and xrange objects. For the moment, we'll only discuss traversal of strings, lists, and tuples.
I. Sequence traversal
There are two kinds of traversal of sequences: one by value and one by index.
1.1 Value traversal:
s='abc'
for x in s:
print x
z=('andy','leaf')
for x in z:
print x
z={'tree','leaf'}
for x in z:
print x
1.2 Index traversal:
l='abcd'
for x in range(len(l)):
print l[x]
l=('andy',22)
for x in range(len(l)):
print l[x]
l={'andy','22'}
for x in range(len(l)):
print l[x]
Second, dictionary traversal
Dictionaries are the only mapping type in python, storing data in key-value pairs. Python performs hash function operation on key, and determines the storage address of value according to the result of calculation, so the dictionary is stored out of order, and the key must be hashable. Hashable keys must be immutable, such as numbers, strings, tuples containing only immutable elements.
2.1 Traversing key:
dir={'andy':'22','leaf':'20'}
for x in dir:
print x
2.2 Traverse value:
dir={'andy':'22','leaf':'20'}
for x in dir:
print dir[x]
2.3 Traversing key + value:
Method 1:
dir={'andy':'22','leaf':'20'}
for x in dir:
print x+':'+dir[x]
Method 2:
d={'zhang':'22','tao':'20'}
for x,y in d.items():
print x,y
At this point, the study of "Python sequence traversal and dictionary traversal implementation method" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!