Iterations in Python

Source: Internet
Author: User

#the For loop of an iterative python can be used not only on a list or a tuple, but also on other objects that can iterate. #list This data type although there is subscript, but many other data types are not subscript, but as long as the object can be iterated, whether or not subscript, can iterate, such as dict can iterate:D = {'a': 1,'b': 2,'C': 3} forKeyinchD:Print(Key)#because Dict storage is not ordered in list order, the resulting order of the iterations is likely to be different. #by default, the Dict iteration is key. If you want to iterate over value, you can use for value in D.values (), if you want to iterate both key and value at the same time, you can use a for-K, V in D.items ().  forValueinchd.values ():Print(value) forKvinchD.items ():Print(k, v)#because a string is also an iterative object, it can also be used for A For loop: forChinch 'ABC':    Print(CH)#So, when we use a For loop, as long as it works on an iterative object, the for loop will work, and we don't care much about whether the object is a list or another data type. #So, how can you tell if an object is an iterative object? The method is judged by the iterable type of the collections module:#determines whether an object is an iterative object fromCollectionsImportIterablet= Isinstance ('ABC', iterable)#whether Str can iteratePrint(t) t= Isinstance ([1, 2, 3], iterable)#whether the list can iteratePrint(t) t= Isinstance (123, iterable)#whether integers can be iteratedPrint(t)#What if you want to implement subscript loops like Java for a list? Python's built-in enumerate function can turn a list into an index-element pair so that both the index and the element itself can be iterated in the For loop: forI, ValueinchEnumerate (['A','B','C']):    Print(i, value)#0 A#1 B#2 CPrint('--------------------------------')#The above for loop, which also references two variables, is common in python, such as the following code: forX, yinch[(1, 1), (2, 4), (3, 9)]:    Print(x, y)

Iterations in Python

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.