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

Advanced features of Python: slicing, iteration, list generation, generator, iterator.

編輯:Python

section

L = ['a','b','c','e','f']
# Take the first three 
print(L[0:3])
print(L[:3])
# Take the last two 
print(L[-2:])
print(L[-2:-1])
# Generate List
L = list(range(20))
# front 10 Number One out of two 
print(L[0:10:2])
# Copy 
print(L[:])
# String slice 
S = "ABCDEFG"
print(S[0:2])
print(S[::2])

[Running] python -u "c:\Users\HP\Desktop\ Learning documents \AI\AI Study github\test.py"
['a', 'b', 'c']
['a', 'b', 'c']
['e', 'f']
['e']
[0, 2, 4, 6, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
AB
ACEG
[Done] exited with code=0 in 0.084 seconds

iteration

L = ['a','b','c','e','f'] # Define a linked list 
T = ('g','h','j','k','l') # Define a tuple 
# iteration 
for ch in L:
print(ch)
for ch in T:
print(ch)
# Define a dictionary 
D = {
'a':1,'b':2,'c':3}
for key in D: # iteration key
print(key)
for value in D.values(): # iteration value 
print(value)
for value in D.items(): # iteration item
print(value)
# How to determine whether an iteration is possible 
# The way is through collections.abc Modular Iterable Type judgment :
from collections.abc import Iterable
print(isinstance(D, Iterable))
print(isinstance(L, Iterable))
print(isinstance(T, Iterable))
print(isinstance(123, Iterable))
# Reference two variables at the same time 
for x, y in [(1, 1), (2, 4), (3, 9)]:
print(x, y)
[Running] python -u "c:\Users\HP\Desktop\ Learning documents \AI\AI Study github\test.py"
a
b
c
e
f
g
h
j
k
l
a
b
c
1
2
3
('a', 1)
('b', 2)
('c', 3)
True
True
True
False
1 1
2 4
3 9
[Done] exited with code=0 in 0.116 seconds

List generator

# Generate list 
L = list(range(10))
print(L)
# Generate x*x List of results 
L = [x * x for x in range(1, 11)]
print(L)
# Filter even number of results Be careful : With the for hinder if It's a screening condition , You can't take else
L = [x * x for x in range(1, 11) if x % 2 == 0]
print(L)
# Generate full permutations 
L = [x+y+z for x in "123" for y in "456" for z in "789" ]
print(L)
# Convert all strings to integers 
L1 = [int(x) for x in L]
print(L1)
# Access the current directory 
import os
L = [d for d in os.listdir('.')]
print(L)
# All strings are lowercase 
L = ['Hello', 'World', 'IBM', 'Apple']
L1 = [s.lower() for s in L]
print(L1)
# A list generator that can be filtered 
L = [x if x%2==0 else -x for x in range(1,20)]
print(L)
# Filter characters 
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s,str)]
print(L2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[4, 16, 36, 64, 100]
['147', '148', '149', '157', '158', '159', '167', '168', '169', '247', '248', '249', '257', '258', '259', '267', '268', '269', '347', '348', '349', '357', '358', '359', '367', '368', '369']
[147, 148, 149, 157, 158, 159, 167, 168, 169, 247, 248, 249, 257, 258, 259, 267, 268, 269, 347, 348, 349, 357, 358, 359, 367, 368, 369]
['ai-edu', 'test.py']
['hello', 'world', 'ibm', 'apple']
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10, -11, 12, -13, 14, -15, 16, -17, 18, -19]
['hello', 'world', 'apple']

generator

# To create a generator, There are many ways . The first method is simple , Just put a list into a generative [] Change to (), You create a generator
#generator The saved algorithm , Every time you call next(g), Just figure it out g The value of the next element of , Until the last element , Without more elements , Throw out StopIteration Error of .
G = (x * x for x in range(10))
for i in G:
print(i)
# Fibonacci sequence 
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'
fib(10)
#generator function : To put fib Functions into generator function , Only need to print(b) Change it to yield b That's all right. 
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
F = fib(10)
print(F)
for i in F:
print(i)
# Yanghui triangle 
def triangles():
L = [1]
while True:
yield L
L=[1]+[L[n] + L[n+1] for n in range(len(L)-1)]+[1]
n = 0
results = []
for t in triangles():
results.append(t)
n = n+1
if n == 10:
break
for i in results:
print(i)
# Be careful call generator The function creates a generator object , Multiple calls generator The function creates multiple independent generator.
[Running] python -u "c:\Users\HP\Desktop\ Learning documents \AI\AI Study github\test.py"
0
1
4
9
16
25
36
49
64
81
1
1
2
3
5
8
13
21
34
55
<generator object fib at 0x000002034C2C4890>
1
1
2
3
5
8
13
21
34
55
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
[Done] exited with code=0 in 0.083 seconds

iterator

Can act directly on for Circular objects are collectively called iteratable objects :Iterable.
One is set data type , Such as list、tuple、dict、set、str etc. ;
One is generator, Including generator and belt yield Of generator function.

from collections.abc import Iterable
from typing import Iterator
print(isinstance([],Iterable)) # list 
print(isinstance({
},Iterable)) # Tuples 
print(isinstance((),Iterable)) # Dictionaries 
print(isinstance("ABC",Iterable)) # character string 
print(isinstance((x for x in range(10)),Iterable)) # List generator 
print(isinstance(100,Iterable)) # Integers False
# Be careful : Generators are Iterator object , but list、dict、str Although it is Iterable, But not Iterator.
# hold list、dict、str etc. Iterable become Iterator have access to iter() function :
print(isinstance([],Iterable))
print(isinstance([],Iterator))
# Generators are Iterator object , but list、dict、str Although it is Iterable, But not Iterator.
# hold list、dict、str etc. Iterable become Iterator have access to iter() function :
print(isinstance([],Iterator))
print(isinstance(iter([]),Iterator))
[Running] python -u "c:\Users\HP\Desktop\ Learning documents \AI\AI Study github\test.py"
True
True
True
True
True
False
True
False
False
True
[Done] exited with code=0 in 0.094 seconds

You may ask , Why? list、dict、str Equal data type is not Iterator?

This is because Python Of Iterator Object represents a data flow ,Iterator Objects can be next() Function call and continue to return the next data , Thrown until no data StopIteration error . You can think of this data flow as an ordered sequence , But we can't know the length of the sequence in advance , It can only be passed continuously next() Function to calculate the next data on demand , therefore Iterator The calculation of is inert , It only calculates if it needs to return the next data .

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 .


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