程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

List generator and iterator of python3 advanced features (3)

編輯:Python

Catalog

List generator

List generated case 1

List generated case 2

List generated case 3

List generated case 4

List generated case 5

iterator (Iterator)

Iteratable object :Iterable

iterator :Iterator

iter() function

Summary


List generator

List generation is List Comprehensions:

yes Python Built in very simple but powerful can be used to create list Generative form of .

List generated case 1

To generate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:

It can be used list(range(1, 11)):

 list(range(1, 11))

The result is :[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

But if you want to generate [1x1, 2x2, 3x3, ..., 10x10] How do you do it? ?

The first method is circulation :

 L = []
for x in range(1, 11):
  L.append(x * x)

The result is :

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

But the cycle is too complicated ,

List generation can use a single line of statements instead of loop generation list:

[x * x for x in range(1, 11)]

The result is :[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

When writing list generation , Put the elements to be generated x * x Put it in front , Followed by for loop , You can put the list created , Simple 、 convenient .

List generated case 2

for You can also add if Judge :

So we can filter out only even squares :

[x * x for x in range(1, 11) if x % 2 == 0]

The result is :[4, 16, 36, 64, 100]

Can generate a full permutation :

[m + n for m in 'ABC' for n in 'XYZ']

The result is :['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

List generated case 3

Use list generation , Can write very simple code .

for example , List all files and directory names in the current directory , It can be implemented in one line of code :

Be careful :os.listdir You can list files and directories

 import os # Import os modular , The concept of modules is discussed later
[d for d in os.listdir('.')]

List generated case 4

for Loops can actually use two or more variables at the same time , such as dict Of items() You can iterate at the same time key and value:

d = {'x': 'A', 'y': 'B', 'z': 'C' }
for k, v in d.items():
   print(k, '=', v)

The result is :y = B    x = A     z = C

therefore , List generation can also use two variables to generate list:

d = {'x': 'A', 'y': 'B', 'z': 'C' }
[k + '=' + v for k, v in d.items()]

The result is :['y=B', 'x=A', 'z=C']

List generated case 5

Put one list All strings in are lowercase :

L = ['Hello', 'World', 'IBM', 'Apple']
[s.lower() for s in L]

The result is :['hello', 'world', 'ibm', 'apple']

iterator (Iterator)

Can act directly on for The data types of the loop are as follows :

One is set data type , Such as list、tuple、dict、set、str etc. ; One is generator, Including generator and belt yield Of generator function.

Iteratable object :Iterable

These can act directly on for Circular objects are collectively called iteratable objects :Iterable.

have access to isinstance() Determine whether an object is Iterable object :

And generators can not only for loop , Can also be next() Function calls continuously and returns the next value , Until the last throw StopIteration An error indicates that the next value cannot be returned .

iterator :Iterator

Can be next() The object that function calls and returns the next value continuously is called an iterator :Iterator.

have access to isinstance() Determine whether an object is Iterator object ,list、dict、str Although it is Iterable, But not Iterator.

iter() function

hold list、dict、str etc. Iterable become Iterator have access to iter() function :

 isinstance(iter('abc'), Iterator)

The result is :True

Iterator It can even represent an infinite data flow , For example, all natural numbers . While using list It's never possible to store all natural numbers .

Summary

What works for The objects of the loop are all Iterable type ; What works next() Function objects are Iterator type , They represent a sequence of lazy calculations ; The collection data type is as follows list、dict、str Is such as Iterable, But it's not Iterator, But it can go through iter() Function to get a Iterator object .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved