python day2
Advanced Features
The less code, the simpler the better
slice slice
A convenient operation
for list and tuple For list, tuple/string slice,
L[0: 3]
L[ : 3]
omit 0
L[-2: -1]
reciprocal cut
L[-2: ]
, omit -1
L[0: 10: 2]
interval, 2
L[:]
copy as it is
iterate
for xxx in xxxx
is similar to java, for each
can iterate everything that can be iterable,
such as list, tuple, dict, string
to determine whether an object is iterable
using collections.Iterable
vars = "aavaefaew"
if isinstance(vars, collections.Iterable):
for var in vars:
print(var)
The default iteration of the dict's key
for value in myDict.values()
iteration value
for k,v in myDict.items()
iteration key-value pair
Iteration with subscripted pairs
for i, v in enumerate(['ahahah', 'kla', 'fawe']):
print(i, v)
The built-in pair enumerate() function converts the list into a pair of index elements
Another method with subscripts
name = ["dfa", "fef"]
for index in range(len(name)):
print(name[index])
for in can have two variables
for x, y in [(1, 2), (3, 4)]:
print(x, y)
for in with else:
the else is executed when the normal for loop ends, and the break is not counted:
for num in range(10, 20):
for i in range(2, num):
if num % i == 0:
j = num / i
print("%d = %d * %d" % (num, i, j))
break
else:
print("%d是一个质数" % (num))
print wraps the line!!!
The way python3 does not wrap is print(x, end = '')
python2print(x,)
gigantic
float('inf')
infinitesimal:
-float('inf')
float('-inf')
list comprehension
Easily and quickly generate a desired list
L = [x * x for x in range(1,11)]
for i in L:
print(i)
You can add if to judge:
L = [x * x for x in range(1,11) if x % 2 == 0]
for i in L:
print(i)
Can be nested:
List = [m + n for m in 'abc' for n in 'xyz']
for i in List:
print(i)
Builder
Using list generation can easily generate a list.
This list takes up memory space.
If the generated list is very large, it is
not cost-effective.
Then , only the algorithm for generating elements is saved, and the elements are calculated when they are used, without occupying a lot of memory, that is, generating The generator object generator
generates the next element through the next() method.
When there are no elements, an error is thrown StopIteration
or the for loop
generator is an iterable object The difference between list comprehension
and () is used instead of []
#列表
List = [m + n for m in 'abc' for n in 'xyz']
for i in List:
print(i)
Generator = (m + n for m in 'abc' for n in 'xyz')
for i in List:
print(i)
In general, next() is not used.
In addition to the method of for () similar to the list comprehension method to generate generator objects, the function with yield can also generate
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n += 1
return 'done'
for i in fib(6):
print(i)
Yang Hui Triangle:
def triangles(max):
L = [1]
n = 0
while n < max:
yield L
L = [1] + [x + y for x, y in zip(L[: -1], L[1:])] + [1]
n += 1
return 'done'
for i in triangles(10):
print(i)def triangles(max):
L = [1]
n = 0
while n < max:
yield L
L = [1] + [x + y for x, y in zip(L[: -1], L[1:])] + [1]
n += 1
return 'done'
for i in triangles(10):
print(i)
iterator
Anything that can be used for is Iterable.
Anything with next() is an Iterator, an iterator object.
Iterator is a lazy sequence
Data types that can be for:
Collection: str, tuple, list, dict, set;
generator, generator function with yield;
Generators are Iterators.
Collections: str, tuple, list, dict, set, etc. can be converted into an iterator object through iter().
functional programming
Python supports some functional programming, but because Python functions have variables, it is not pure functional programming.
Java does not support functional programming.
A Java variable name cannot point to a method, it can only point to basic data types and objects.
Higher order functions
The function name is also a variable; the
function name originally points to a function. If you force a value to the function name, then the function name will not point to the original function.
Don't do it!
Variables can point to functions, and functions can accept variables, so the variable name received by the function points to a function, which is a higher-order function. function set function.
That is, let the parameters of the function accept other functions, and this function is a higher-order function.
def add(a, b, f):
return f(a) + f(b);
num = add(-11, -2, abs)
print(num)
map
map(function, Iterable)
returns an Iterator
that applies the function to each element of the Iterable and returns an Iterator
def f(x):
return x * x;
Iterator = map(f, [1, 2, 3, 4])
for i in Iterator:
print(i)
reduce
reduce(function, Iterable)
applies the function to the result of the first two elements, and then to the third element.
import functools
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2int(c):
return DIGITS[c]
return functools.reduce(fn, map(char2int, s))
print(str2int("12355478"))
lambda expression:
import functools
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2int(c):
return DIGITS[c]
def str2int(s):
return functools.reduce(lambda x, y : x *10 + y , map(char2int, s))
print(str2int("12355478"))
Use the map() function to change the non-standard English name input by the user into uppercase first letter and other lowercase canonical names. Input: ['adam', 'LISA', 'barT'], Output: ['Adam', 'Lisa', 'Bart']:
def normalize(name):
return list(map(lambda n : n[: 1].upper() + n[1:].lower(), name))
L1 = ['adam', 'LISA', 'barT']
L2 = normalize(L1)
print(L2)
The sum() function provided by Python can accept a list and sum, please write a prod() function that can accept a list and use reduce() to calculate the product:
import functools
def prod(L):
return functools.reduce(lambda x, y : x * y, L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
Write a str2float function using map and reduce to convert the string '123.456' to a floating point number 123.456:
# -*- coding: utf-8 -*-
import functools
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2int(c):
return DIGITS[c]
def str2float(s):
a, b = s.split(".")
return functools.reduce(lambda x, y: x * 10 + y, map(char2int, a)) + functools.reduce(lambda x, y: x / 10 + y,
map(char2int, b[: : -1])) / 10
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
filterfilter
Iterator filter(function, Iteratable)
returns a lazy Iterator
def _odd_iter():
n = 1
while True:
n += 2
yield n
def _nature_iter():
n = -1
while True:
n += 1
yield n
def _not_divisible(n):
return lambda x: x % n > 0
def primes():
it = _nature_iter()
next(it)
next(it)
while True:
n = next(it)
yield n
it = filter(_not_divisible(n), it)
for n in primes():
if n < 1000:
print(n, end=', ')
else:
break