Python Looping Tips

Source: Internet
Author: User
Tags pear

Original address: Http://docs.pythontab.com/python/python3.4/datastructures.html#tut-tuples

When looping in a dictionary, the keywords and corresponding values can be interpreted at the same time using the Iteritems () method.

Knights = {'gallahad'' Thepure'Robin  'thebrave' for in Knights.items ():     Print (K,V)

The-------output is as follows-------------------------

Robin the Brave
Gallahad the Pure

When looping through a sequence, the index position and corresponding value can be obtained at the same time using the enumerate () function.

 for  in Enumerate (['tic'tac'toe  ']):    print(i,v)

The------output is as follows------------------------------

0 Tic
1 TAC
2 Toe



Looping two or more sequences at the same time, you can use the zip () package as a whole.

Questions = ['name','Quest','Favorite Color']answers= ['Lancelot','The Holy Grail','Blue'] forQ,ainchZip (questions,answers):Print("{0},{1}". Format (Q,a))


The------output is as follows----------------------------------

Name,lancelot
Quest,the Holy Grail
Favorite Color,blue

If a reverse loop sequence is required, the sequence is positioned first, and then the reversed () function is called.

 for  in Reversed (range (1,10,2)):    print(i)
The------output is as follows----------------------------------

9
7
5
3
1

To loop through the sequence in sorted order, use the sorted () function, which does not alter the original sequence, but instead generates a new sorted sequence.

 basket = [  apple   ' ,  '  orange  ,  '  pear   ' ,  '  orange   ' ,  '  banana   '   '  for  F in   sorted (set (basket)):  print  (f) 
The------output is as follows----------------------------------

Apple
Banana
Orange
Pear

Python Looping Tips

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.