Python iteration, List-generation

Source: Internet
Author: User

Iteration:

An iterative object (iterable) that can directly act on a For loop object, such as a LIST/TUPLE/DICT/SET/STR/etc collection data type that can directly act on a for loop

>>> spam={1: ' A ', 2: ' B ', 3: ' C '}>>> for x in spam:                                         #默认情况下, dict iteration is Keyprint x123>>> for Value in Spam.values ():                            #values (): Iteration valueprint valueabcfor k,v in Spam.items ():                                   #items (): Iteration key-value print K,v1 A2 B3 C

How can I tell if an object is an iterative object? The method is judged by the iterable type of the collections module:

>>> from collections import iterable               #导入collection模块 >>> isinstance (' abc ', iterable)                     # Isinstance (): Determines whether an object is iterator object True >>> isinstance ([1,2,3],iterable) true>>> isinstance (123, iterable) False 

Simplified iterations: List-generated

Remove a string from the list and convert it to lowercase
>>> L1 = [' Hello ', ' World ', ' mac ', none]l2 = [X.lower () for x in L1 if Isinstance (x,str)]                #isinstance () : Determine if string >>> l2[' Hello ', ' world ', ' Apple '

The or loop can be followed by an if judgment so that we can filter out only the even squares:

>>> [x * x for x in range (1, one) if x% 2 = = 0][4, 16, 36, 64, 100]

Python iteration, List-generation

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.