Python 在问答频道中刷题积累到的小技巧(二)

简介: Python 在问答频道中刷题积累到的小技巧(二)

1. 读出Python彩蛋《The Zen of Python》并写入文件:

from this import s,d
txt = ''
for t in s:
    txt += d.get(t,t)
with open('zen.txt','w') as f:
    f.write(txt)
print('\nThe Zen of Python is written to a file named "zen.txt".')

输出结果:

'''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
The Zen of Python is written to a file named "zen.txt".
'''





2. 内置函数sum()可以用于“列表降维”的来龙去脉

原理分析:

>>> # sum(iterable, start=0) --> 返回值:start + sum(iterable)
>>> sum([1,2,3])
6
>>> sum([1,2,3], start=5)
11
>>> # = start + sum([1,2,3]) # start在前是原因的
>>> sum([1,2,3], -5)
1
>>> sum([[1,2,3],[4,5]],[6]) # 换成列表的加法
[6, 1, 2, 3, 4, 5]
>>> [6]+[1,2,3]+[4,5]
[6, 1, 2, 3, 4, 5]
>>> sum([[1,2,3],[4,5]],[]) # 这就是第2参数用个空列表就能降维列表的原因
[1, 2, 3, 4, 5]


应用:倍容列表 [1,2,3,4,5] -> [1,1,2,2,3,3,4,4,5,5]

>>> listn = lambda ls,n=2:sum(map(lambda x:[x]*n,ls), [])
>>> a = [*range(1,5)]
>>> a
[1, 2, 3, 4]
>>> listn(a,3)
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
>>> [i//3 for i in range(3*5+1)]
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5]
>>> [i//3 for i in range(3*5)]
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
>>> [i//3+1 for i in range(4*3)]
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
>>> [1+i//3 for i in range(4*3)]
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
>>> a = [*range(1,5)]
>>> a
[1, 2, 3, 4]
>>> listn = lambda ls,n:sum(map(lambda x:[x]*n,ls),[])
>>> listn(a,3)
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
>>> [1+i//3 for i in range(4*3)] # 整数列表用整除运算推导也容易
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
>>> listn('abcde',3)
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e']



应用:读出文本文件中所有单词(文件中无标点)

with open('sentence.txt', 'r') as f:
    data = f.read()
scores = sum([s.split() for s in data.split('\n')], [])
for s in scores:
    print(s)


3. 某瓣电影排名的榜单排序(一对多字典,由于键的唯一性对应键值用列表)


   题目内容:


   “我们导出了某瓣电影排名的 top250,现要统计不同导演所导演的电影在榜单中的数量,按照导演的电影数量排序,将导演的电影数量大于等于 3 的导演以及其导演的电影,使用 print 函数输出到屏幕。要求格式化对齐输出。”



import pandas as pd
df = pd.read_csv('某瓣电影排行榜.csv')
lis = [(director,film) for director,film in zip(df['导演'],df['影名'])]
dic = {}
for i,n in enumerate(lis):
    dic[n[0]] = dic.get(n[0], []) + [lis[i][1]] # 技巧点 ,当然pandas会有更好直接筛选方法
for k,v in sorted(dic.items(),key=lambda x:len(x[1]), reverse=True):
    if len(v)>=3:
        print(f"【导演】:{k}\n【片数】:{len(v)}\n【作品】:{' '.join(dic[k])}\n")


注:抽空把没过的下载来看看 ^_^

(续上题)不用循环遍历,快速生成字典且降序排列

lst = df["导演"].tolist()
import numpy as np
dict(sorted(dict(zip(*np.unique(lst, return_counts=1))).items(),key=lambda x:x[1],reverse=True))
from collections import Counter
dict(Counter(lst))  # 当然Counter()更简单,返回的就是降序字典


4. 简洁、对称又好理解的二叉树遍历代码

class bTree:
    def __init__(self, rooot=None, lchild=None, rchild=None):
        self.root = root
        self.left = lchild
        self.right = rchild
    def __repr__(self):
        if not (self.left or self.right): return f'{self.root}'
        return f'[{self.left if self.left else "-"}<{self.root}>{self.right if self.right else "-"}]'
    def preOrder(self):
        '''前序遍历'''
        if not self: return []
        return [self.root]+bTree.preOrder(self.left)+bTree.preOrder(self.right)
    def inOrder(self):
        '''中序遍历'''
        if not self: return []
        return bTree.inOrder(self.left)+[self.root]+bTree.inOrder(self.right)
    def postOrder(self):
        '''后序遍历'''
        if not self: return []
        return bTree.postOrder(self.left)+bTree.postOrder(self.right)+[self.root]
    def Height(self):
        if not self: return 0
        lH = bTree.Height(self.left)
        rH = bTree.Height(self.right)
        return max(lH,rH)+1
exp = bTree('+')
exp.left  = bTree('*')
exp.right = bTree('/')
exp.left.left   = bTree(1)
exp.left.right  = bTree(2)
exp.right.left  = bTree(3)
exp.right.right = bTree(4)
order = exp.inOrder()
print(order)
tmp = ' '.join(map(str,order))
print(tmp,'=',eval(tmp))
print(exp)
print(repr(exp))
print(exp.preOrder())
print(exp.postOrder())



目录
相关文章
|
10月前
|
存储 索引 Python
Python小技巧:单下划线 '_' 原创
Python小技巧:单下划线 '_' 原创
134 3
|
11月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
229 2
|
8月前
|
自然语言处理 Python
使用Python和Qwen模型实现一个简单的智能问答Agent
使用Python和Qwen模型实现一个简单的智能问答Agent
749 4
|
10月前
|
开发者 索引 Python
7个提升python编程的小技巧
7个提升python编程的小技巧
107 1
7个提升python编程的小技巧
|
9月前
|
搜索推荐 Python
Leecode 101刷题笔记之第五章:和你一起你轻松刷题(Python)
这篇文章是关于LeetCode第101章的刷题笔记,涵盖了多种排序算法的Python实现和两个中等难度的编程练习题的解法。
82 3
|
10月前
|
开发工具 git Python
Python小技巧:满意的逗号放置
Python小技巧:满意的逗号放置
54 4
|
9月前
|
算法 C++ Python
Leecode 101刷题笔记之第四章:和你一起你轻松刷题(Python)
这篇博客是关于LeetCode上使用Python语言解决二分查找问题的刷题笔记,涵盖了从基础到进阶难度的多个题目及其解法。
81 0
|
9月前
|
算法 C++ Python
Leecode 101刷题笔记之第三章:和你一起你轻松刷题(Python)
本文是关于LeetCode算法题的刷题笔记,主要介绍了使用双指针技术解决的一系列算法问题,包括Two Sum II、Merge Sorted Array、Linked List Cycle II等,并提供了详细的题解和Python代码实现。
88 0
|
9月前
|
算法 C++ 索引
Leecode 101刷题笔记之第二章:和你一起你轻松刷题(Python)
本文是关于LeetCode 101刷题笔记的第二章,主要介绍了使用Python解决贪心算法题目的方法和实例。
75 0
|
10月前
|
存储 索引 Python
Python小技巧:单下划线 ‘_‘
Python小技巧:单下划线 ‘_‘
69 0

推荐镜像

更多