python刷题和学习笔记

来源:互联网 发布:公安部防网络诈骗中心 编辑:程序博客网 时间:2024/05/22 03:32

常见代码

result = map(lambda x: int(x), input().split())print(list(result))  # 输入1 2 3,得到列表[1,2,3],这里使用split()比split(' ')更能容错# 如果使用了' ',那么输入必须严格按照一个空格,并且最后一个数字后面不可以有空格。print('Hello' if True else 'World')  # Helloprint('Hello' if False else 'World')  # Worlda = [1,2,3,4]a[1:1] = [0,0,0]  # [1, 0, 0, 0, 2, 3, 4]甚至是a[1:0]都是有效的操作# 对字典遍历,如果没有使用字典的items,keys,values函数,默认遍历的也是keycosts = {'fin': inf, 'a': 6, 'b': 2}for cost in costs:    print(cost, end=' ')    node = costs(cost)# fin a b# 如果是costs,而不是costs.items(),比如上面的的cost其实就是键的值。costs(cost)得到value。# 初始化链表class Node:    def __init__(self, value, next=None):        self.value = value        self.next = nextL = Node('a', Node('b', Node('c')))list x = [1,2,3]tuple x = (1,2,3)set x = {1,1,2,3} # {1,2,3}python -i test.py执行之后,源码中使用的变量会继续驻留在交互式的解释器中,可以继续使用。浮点数比较问题from decimal import *sum(Decimal('0.1') for i in range(10)) == Decimal('1.0')def almost_equal(x, y, places=7):    return round(abs(x-y), places=7)==0almost_equal(sum(0.1 for i in range(10), 1.0)

列表

append是把一个元素加入到列表的最后,extend是把一个元素中包含的元素加入到列表后面,所以extend的对象是要可迭代的。如果extend的是一个字符串,那么字符串拆分成一个一个字符加入到列表中。

data = ['Hello', '2018', 'New Year']print(data, sep=',')  # ['Hello', 2018, 'New Year']print(*data, sep=',')  # Hello,2018,New Year

enumerate

items = ['a', 'b', 'c']for id, value in enumerate(items, 1):  # 1是设置输出id的起始值    print(id, value)  # 1 a 2 b 3 cdata = [(1, 2), (3, 4), (5, 6), (7, 8)]# 不可以for index, x, y in ...for index, (x, y) in enumerate(data):      print(index, x, y)

列表逆序

nums = [1, 2, 3, 4, 5]nums_re = nums[::-1]print(nums_re)  # [5, 4, 3, 2, 1]nums.reverse()print(nums)  # [5, 4, 3, 2, 1]nums_re = reversed(nums)print(list(nums_re))  # [1, 2, 3, 4, 5]

列表展开

import itertoolsa = [[1, 2], [3, 4], [5, 6]]# 1s = list(itertools.chain.from_iterable(a))s = list(itertools.chain(*a))# 2s = sum(a, [])# 3s = [x for L1 in a for x in L1 ]# 4func = lambda x: [y for t in a for y in func(t)] if type(x) is list else [x]func(a)# 5from collections import Iterabledef flatten(items, ignore_type=(str, bytes)):    for x in items:        if isinstance(x, Iterable) and not isinstance(x, ignore_type):            yield from flatten(x)            #如果不用yield from            # for i in flatten(x):            #     yield i        else:            yield xitems = [1, 2, [3, 4, [5, 6], 7], 8]print(list(flatten(items)))  # [1, 2, 3, 4, 5, 6, 7, 8]

复制列表

new_list = old_list[:]new_list = list(old_list)import copynew_list = copy.copy(old_list)new_list = copy.deepcopy(old_list)# 关于deepcopyimport copyorigin = [1, 2, [3, 4]]copy1 = copy.copy(origin)copy2 = copy.deepcopy(origin)print(id(origin))print(id(copy1))print(id(copy2))# 不同的内存地址print(copy1 == copy2)print(copy1 is copy2)origin[0] = 11print(origin, copy1, copy2)# [11, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]]origin[2][0] = 'ok'print(origin, copy1, copy2)# [11, 2, ['ok', 4]] [1, 2, ['ok', 4]] [1, 2, [3, 4]]origin.append(5)print(origin, copy1, copy2)# [11, 2, ['ok', 4], 5] [1, 2, ['ok', 4]] [1, 2, [3, 4]]# copy对于一个复杂对象的子对象不会完全复制,比如序列中的序#列,字典里的序列等,这样的子对象在copy之后作为一个公共的部#分使用。比如子对象append元素在原序列也会体现,但对copy对象#append在原序列则不会体现。# deepcopy得到的是和原来完全独立的list,shallow #copy只有修改其中包含的list中的元素,这样的修改才会影响到#copy的list。a = [1, 2, 3]b = aa = [4, 5, 6]print(a, b)  # [4, 5, 6] [1, 2, 3]a = [1, 2, 3]b = aa[0], a[1], a[2] = 4, 5, 6print(a, b)  # [4, 5, 6] [4, 5, 6]# 为什么有上面这个现象呢?对于第一种情况,a = [1, 2, 3], b = a之后,相当于a和b两个标签指向了一块存放1,2,3的内存区域,当a = [4, 5, 6]时,a就指向了另一块区域了。而第二种情况是直接把a指向的内存区域做了修改,所以a和b都发生的变化。

自定义列表排序

1. 原列表改变items.sort(key = lambda item: item.get('age'), reverse=True)2. 原列表不改变new_items = sorted(items, key = lambda item: item.get('age'), reverse=True)

删除元素

items.remove(value)     #删除第一次出现的valuedel items[index]        #删除指定位置的items.pop(index)        #删除指定位置的

列表中随机选择

import randomrandom.choice(items)

zip函数

矩阵转置mat = [[1, 2, 3], [4, 5, 6]]s = zip(*mat)# print(list(s))  # [(1, 4), (2, 5), (3, 6)]列表的联合list1 = ['a', 'b', 'c', 'd']list2 = ['p', 'q', 'r', 's']for x, y in zip(list1, list2):    print(x, y)  # a p, b q, ...压缩和解压缩a = [1, 2, 3]b = ['a', 'b', 'c']z = zip(a, b)# print(list(z))s = zip(*z)print(list(s))这里zip压缩后得到的zip对象似乎是类似generator对象一样,只可以使用一次。比如如果print(list(z))执行了的话,后面的解压说得到的结果为空列表。同样,如果在解压缩之后print(list(z))输出为空。高级用法a = [1, 2, 3, 4, 5, 6]s = zip(*([iter(a)] * 2))print(list(s))  # [(1, 2), (3, 4), (5, 6)]# 根据上面的group_adjacent = lambda a, k: zip(*[iter(a)] * k)s = group_adjacent(a, 3)print(list(s))  # [(1, 2, 3), (4, 5, 6)]zip(a[0::3], a[1::3], a[2::3])  # [(1, 2, 3), (4, 5, 6)]# 根据上面的group_adjacent = lambda a, k: zip(*(a[i::k] for i in range(k)))s = group_adjacent(a, 3)print(list(s))  # [(1, 2, 3), (4, 5, 6)]s = [iter(a[i:]) for i in range(2)]  #  这一步得到两个列表[1,2,3,4,5,6]和[2,3,4,5,6]print(list(zip(*s)))  # [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]def n_grams(a, n):    z = [iter(a[i:]) for i in range(n)]    return zip(*z)s = n_grams(a, 4)print(list(s))  # [(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]

反转字典(键值反转)

m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}print(m.keys())print(m.values())s = zip(m.values(), m.keys())# print(list(s))  # 需要记住的就是如果对s执行list函数,后面在执行结果就是空了,所以可以不要把zip结果放在变量中存放,以免后面操作忘记了# print(dict(list(zip(m.values(), m.keys()))))print(dict(list(s)))# 更简单点的s = {v: k for k, v in m.items()}print(s)

进制

input_hex = input()to_dec = int(input_hex, 16)  #用户输入16进制,把16进制转10进制。dec = int(input("输入数字:"))print("十进制数为:", dec)  #输出:5print("转换为二进制为:", bin(dec))  #输出:0b101print("转换为八进制为:", oct(dec))  #输出:0o5print("转换为十六进制为:", hex(dec))  #输出:0x5

字符串

0 基础

print('Hello'*2)  # HelloHello

1 逆序

input_line = input()input_line_re = list(reversed(input_line))# 或者input_line_re = input_line[::-1]

2 统计字符出现的次数

'abcabc'.count('a')

3 列表元素组合成字符串输出

print(''.join(input_number))

join方法是将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串,比如[‘a’, ‘b’, ‘c’]执行’,’.join(list)函数得到的是a,b,c,是在元素之间插入分割符。

迭代器和生成器

可以用在for .. in ..语句中的都是可迭代的,比如list、string、file等,这些课迭代的对象可以随意的读取,因此所有的值都放在了内存中。
generator也是迭代器的一种,但是它们值可以迭代一次。因为它们不是全部存放在内存中的,它们是在调用的时候在内存中才生成的。包含yield语句的函数返回的就是一个生成器。

class Bank():    crisis = False    def create_money(self):        i = 0        while not self.crisis:            i += 1            yield iatm = Bank()creator = atm.create_money()print(next(creator))  # 1atm.crisis = True# print(next(creator))  # exceptionatm.crisis = Falseprint(next(creator))  # 2 

collections

1 Counter

Counter是collections类库里内置的dict类的子类

from collections import Counteritems = [1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7]s = Counter(items)print(s)  # Counter({3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1, 7: 1})print(s.most_common(3)) # [(3, 4), (1, 2), (2, 2)]

2 namedtuple

Point = namedtuple('Point', ['x', 'y'])p = Point(x=1, y=2)print(p.x)class Point(namedtuple('PointBase', ['x', 'y'])):    # __slots__ = ()    def __add__(self, other):        return Point(x=self.x+other.x, y=self.y+other.y)p1 = Point(x=1, y=2)p2 = Point(x=2, y=3)q = p1 + p2print(q)  # Point(x=3, y=5)

3 deque

from collections import dequeq = deque(maxlen=3)q.append(2)q.appendleft(1)q.appendleft(0)# print(q)  # deque([0, 1, 2], maxlen=3)q.appendleft([5,6])# print(q)  # deque([[5, 6], 0, 1], maxlen=3)q.extendleft([5,6])# print(q)  # deque([6, 5, [5, 6]], maxlen=3)

4 OrderedDict

heapq

1 nlargest/nsmallest

import heapqnums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]n_largest = heapq.nlargest(3, nums)  # [42, 37, 23]n_smallest = heapq.nsmallest(3, nums)  # [-4, 1, 2]

itertools

1 全排列

from itertools import permutationsitems = ['a', 'b', 'c']for p in permutations(items):  # permutations(items)得到的是一个itertools.permutations object    print(p)  # 全排列for p in permutations(items, 2):    print(p)  # 会输出6个,a,b和b,a都输出

2. 组合

from itertools import combinationsfor c in combinations(items, 3):    print(c)  # ('a', 'b', 'c'),组合只有一种for c in combinations(items, 2):    print(c)  # 只有三种for c in combinations(items, 1):    print(c)  # ('a',) ('b',) ('c',) 为什么有逗号?from itertools import combinations_with_replacementfor c in combinations_with_replacement(items, 3):    print(c)  # 考虑元素重复的情况,比如('a', 'a', 'a') ('a', 'a', 'b')....