Python 骚操作


import random
from functools import reduce
from collections import Iterator, Iterable
from collections import defaultdict
from collections import Counter, ChainMap, OrderedDict, namedtuple, deque


"""Map数字案例"""
num = [1, 2, 3, 4, 5, 6, 7, 8, 9]
num = list(map(lambda x: x + 1, num))
print(num)

"""Map字符串案例"""
strls = ['dongli', 'jiamei', 'dongdong']
strls = list(map(lambda x: x.upper(), strls))
print(strls)

"""filter数字案例"""
num = list(map(lambda x: x, range(10)))
num = list(filter(lambda x: x if x > 5 else None, num))
print(num)

"""filter 字符串案例"""
strls = ['dongli', 'jiamei', 'dongdong']
char = list(filter(lambda x: x if x == 'dongli' else None, strls))
print(char)

"""reduce序列连加 需要倒入reduce"""
num = [x for x in range(1, 101)]
num = reduce(lambda x, y: x+y, num)
print(num)

"""
    - iterator, iterable, generator
"""

iters = (x for x in range(100))
print(next(iters))
print(next(iters))
print(next(iters))


def iter_demo():
    yield 8
    yield 88 
    yield 888

a = iter_demo()
print(next(a))
print(next(a))
print(next(a))

"""把list转换为iter"""

ls = [i for i in range(10)]
print(iter(ls))
it = iter(ls)
print(next(it))
print(next(it))
print(next(it))

dic = {1: 2, 2: 3, 3: 4}
dic = iter(dic.items())
print('*'*10)
print(next(dic))
print(next(dic))


"""判断是否是迭代器或者可迭代对象 需要倒入"""

a = [1, 2, 3]

print(isinstance(a, Iterable))
print(isinstance(a, Iterator))

b = {1: 2, 2: 3, 3: 4}
print(isinstance(b, Iterable))
print(isinstance(b, Iterator))
print(isinstance(dic, Iterator))
print(isinstance(range(10), Iterable))
print(isinstance(range(10), Iterator))


"""生成器 斐波那契 """


def num(num):
    a = 0
    b = 1
    while a < num:
        yield a
        a, b = b, a+b

for i in num(100):
    print(i)

"""大文件处理"""
with open('text.log', 'w') as f:
    for i in range(500):
        f.write(''.join([str(random.randint(1, 10)) for _ in range(1, 10)])+'\n')

with open('text.log') as f:
    for i in f:
        print(i)
        break

"""列表推导式,生成器表达式"""

ls_push = [i for i in range(10)]
dic_push = (i for i in range(10))
print(ls_push, dic_push)

""" Lambda 表达式 """
f = lambda x: x*2
print(f(2))

f = lambda x: True if x > 2 else None
print(f(1))
print(f(4))

f = lambda x, y: x+y
print(f(1, 2))

# user_info = {'name': 'dongli', 'name': 'jiamei', 'name': 'dongdong'}
user_info = [('dongli', 20), ('jiamei', 17)]
user_info.sort(key=lambda x: (x[1], x[0]))  # 没有返回值 直接修改原序列
print(user_info)

user = ['dongli', 'jiamei', 'hmm']
user.sort(key=None, reverse=True)  # 倒序
print(user)

""" 默认字典使用lambda"""
d = defaultdict(lambda: 0)
d['name']
print(d)

d = [1, 2, 3, 4, 5, 1]
e = defaultdict(lambda: 0)  # 统计元素出现个数

for i in d: 
    e[i] += 1
print(e)

d = defaultdict(lambda: 'BJ')
d['city']
print(d)

d = defaultdict(lambda: (1,2))
d['point']
print(d)

""" any all max min sum reversed sort"""


def is_num(x, y):
    if any([x > 1, y > 5]):
        return True

n = is_num(4, 1)
print(n)


def is_num(x, y):
    if all([x > 1, y > 5]):
        return True

n = is_num(4, 1)
print(n)

ls = [1, 2, 3, 4, 5]

print(min(ls))
print(max(ls))
print(sum(ls))

ls = [i for i in reversed(ls)]
print(ls)

ls = [i for i in reversed(range(8))]
print(ls)

ls.sort()
print(ls)

new_ls = sorted(reversed(ls))  # sorted 返回一个新的序列
print(new_ls)


ls = [1, 2, -10, -3, 3, 4, 5]
new_ls = sorted(ls, key=abs)
print(new_ls)

ls1 = [1, 2, 3, 5]
ls2 = ['a', 'b', 'c', 'd', 'e']
ls4 = [6, 7, 8, 9, 0]
ls3 = zip(ls1, ls2, ls4)  # 合并后的元素个数与第一个序列的元素个数为准

print(list(ls3))
print(dict(zip(ls1, ls2)))

""" 字典推导式 """

dic = {'name': 'dongli', 'age': '17'}

dic1 = {k.capitalize(): v.upper() for k, v in dic.items()}
print(dic1)

""" set 去重 """
ls = [1, 2, 3, 4, 53, 2, 3, 34, 4, 52, 1]
print(set(ls))

""" 三元操作符 """

x = [x for x in ["a", "b", "c", "d", "e"] if x == 'a']
print(x)


def is_a(char):
    return 'a' if char == 'a' else '*'

a = is_a('a')
print(a)
a = is_a('b')
print(a)

"""枚举"""

ls = ['add', 'del', 'modify']

for i in enumerate(ls, 1):
    print(i)

""" counter elements subtract most_common"""

s = 'dongli is good'
l = ['dongli', 'jiamei', 'dongli']
print(Counter(s))
print(Counter(l))

s = Counter(s)
print(list(s.elements()))
s.subtract('o')
print(s)
print(s.most_common(3))

""" defauldict """

d = defaultdict(lambda: 0)
print(d[1])

d = defaultdict(int)
print(d[2])
d[3] = 1
print(d)

s = 'dongli is good boy'
d = defaultdict(lambda: 0)

for i in s:
    d[i] += 1

print(d)

d = defaultdict(list)
line = [(3, 6), (4, 8), (3, 7), (5, 5), (4, 10), (5, 10)]

for k, v in line:
    d[k].append(v)

print(d)

""" chainmap """

dic1 = {'a', 'b', 'c', 'd', 'e'}
dic2 = {1, 2, 3, 4, 5}

dic3 = ChainMap(dic1, dic2)
print(dic3)
dic5 = zip(dic1, dic2)
dic4 = {6: 7, 7: 8, 8: 9, 9: 10}

dic4.update(dic5)
print(dic4)

""" ordereDict """

dic = {'e': 3, 'a': 4, 'b': 5, 'f': 7}
dic1 = OrderedDict(sorted(dic.items()))
dic2 = sorted(dic.items(), key=lambda x: x[1])
dic3 = sorted(dic.items())

print(dic1)
print(dic2)
print(dic3)

""" Deque """

d = deque()
d.append(1)
d.appendleft(2)
print(d)
d.append(3)
d.append(4)
d.rotate(-1)
print(d)

d = [i for i in range(8)]
d = deque(d, 3)
print(d)

with open('text.log', 'r') as f:
    print(deque(f, 3))

""" nametuple """

point = namedtuple('point', ('x', 'y'))
print(point(4, 8))

point = namedtuple('point', ['x', 'y'])
print(point(3, 6))

point = namedtuple('point', 'x,y')
print(point(1, 1))
p = point(2, 2)
print(p.x + p.y)

最后更新于:2018-06-09 11:00:31