Python Index iterations

Source: Internet
Author: User

1. Using the Enumerate function

  
 
  1. L = [‘Adam‘, ‘Lisa‘, ‘Bart‘, ‘Paul‘]

  2. for index, name in enumerate(L):

  3.     print index + 1, ‘-‘, name.lower()

2. Using the Zip function
  
 
  1. for  index  NAME  in  zip ( range ( 1 Span class= "pun",  len ( l 1  l

  2.     print index, ‘-‘, name

3. dict element Iteration Access

  
 
  1. d = {
  2. ‘Adam‘: 95,
  3. ‘Lisa‘: 85,
  4. ‘Bart‘: 59
  5. }
  6. for (key, value) in d.items():
  7. print("%s: %s" % (key, value))
  8. for key in d:
  9. print("%s: %s" % (key, d[key]))
  10. for key, value in zip(d.keys(), d.values()):
  11. print("%s: %s" % (key, value))
If you read the Python document carefully, you can also find that dict in addition to values ()method, there is also a itervalues ()method, with itervalues ()method Overrides values ()method, the iteration effect is exactly the same.
  
 
  1. for key, value in zip(d.iterkeys(), d.itervalues()):
  2. print("%s: %s" % (key, value))

What is the difference between the two methods?

1. The values () method actually converts a dict to a list containing value.

2. However, the itervalues () method does not convert, and it takes value from dict in sequence during the iteration, so the Itervalues () method saves the memory needed to generate the list, compared to the values () method.

3. Print itervalues () find it returns a <dictionary-valueiterator> object, which shows that in Python, thefor loop can be used to iterate beyond list,tuple,str. Unicode,dict, and so on , any iterator object can be used for a for loop, and the inner iteration of how we usually don't care.  



From for notes (Wiz)

Python Index iterations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.