python小例子(一)
参考链接:https://zhuanlan.zhihu.com/p/83998758?utm_source=qq&utm_medium=social&utm_oi=728200852833075200
1.判断是否存在重复元素
def all_unique(a):
return len(a)==len(set(a))
print(all_unique([1,1,2,3]))
输出:False
2.检查两个字符串的组成是否一样,即元素的种类和数目是否一致
def anagram(a,b):
return Counter(a)==Counter(b)
print(anagram("3abcda","acdba3"))
输出:True
3.内存占用
#32位系统
import sys
variable = 38
print(sys.getsizeof(1))
print(sys.maxsize)
输出:14
2147483647
4.字节占用
def byte_size(string):
return len(string.encode("utf-8"))
print(byte_size("hello world"))
输出:11
5.打印N次字符串
print(“a”*3)
输出:aaa
6.大写第一个字母
print("abc".title())
输出:Abc
7.分块
from math import ceil
def chunk(alist,size):
return list(map(lambda x:alist[x*size:x*size+size],
list(range(0,ceil(len(alist)/size)))))
print(chunk([1,2,3,4,5],2))
输出:[[1,2],[3,4],[5]]
8.压缩
使用python filter函数,其一般形式为filter(func,iterable)
例子1:
def is_odd(a):
return a%2==1
print(list(filter(is_odd,[1,2,3,4,5,6,7,8])))
输出:[1,3,5,7]
例子2:
print(list(filter(bool,[False,None,"",0,3,"a"])))
输出:[3,"a"]
9.解包
a=[['a','b'],['c','d'],['e','f']]
print(*a)
输出:
['a','b'] ['c','d'] ['e','f']
for i in zip(*a):
print(i)
输出:
('a','c','e')
('b','d','f')
10.链式对比
a=3
print(2<a<4)
输出:True
print(2==a<4)
输出:False
11.列表转字符串(用逗号相隔)
print(",".join(['a','b','c']))
输出:a,b,c
12.元音统计(正则表达式的一种应用)
import re
print(re.findall("[aeiou]","foobar"))
输出:3
13.展开列表
a=[1,[2],[[3],4],5]
def spread(a):
res=[]
for i in a:
if isinstance(i,list):
res.extend(i)
else:
res.append(i)
return res
def deep_flatten(b):
result=[]
result.extend(spread((list(map(lambda x:deep_flatten(x) if type(x)==list else x,b)))))
return result
print(deep_flatten(a))
输出:[1,2,3,4,5]
14.列表的差(返回第一个列表的元素,不再第二个列表中的)
def diff(a,b):
set_a=set(a)
set_b=set(b)
comparison=set_a.difference(set_b)
return list(comparison)
print(diff([1,2,3],[1,2,4]))
输出:[3]
15.通过函数取差(如下方法会先应用一个给定的函数,然后再返回应用函数后结果有差别的列表的元素)
import math
def difference_by(a,b,fn):
b=set(map(math.floor,b))
return [item for item in a if math.floor(item) not in b]
print(difference_by([1.2,2.1],[2.3,3.4],math.floor))
输出:[1.2]
16.函数的链式调用(可以再一行代码内调用多个函数)
def add(a,b):
return a+b
def substract(a,b):
return a-b
a,b=4,5
print((substract if a>b else add)(a,b))
输出:9
17.判断列表是否有重复值
print(len([1,2,2,3]==len(set([1,2,2,3])))
输出:False
18.合并两个字典
def merge_two_dicts(a,b):
c=a.copy()
c.update(b)
return c
print(merge_two_dicts({1:2},{3:4}))
输出:{1:2,3:4}
再pyhton3.5及以上,直接print({**{1:2},**{3:4}})
19.把两个列表转换成字典
def to_dictionary(a,b):
return dict(zip(a,b))
print(to_dictionary(["a","b"],[1,2]))
输出:{"a":1,"b":2}
20.使用枚举(能够同时取到index和value)
a=["a","b"]
for index,val in enumerate(a):
print(index,val)
输出:
0 a
1 b
21.执行时间(计算执行特定代码所用的时间)
import time
start_time=time.time()
for i in range(10000):
print(i)
end_time=time.time()
total_time=end_time-start_time
print(round(total_time,2))
输出:0.17
22.Try else(可以多加一个else,如果没有触发错误,这个子句就会被执行)
try:
2*3
except TypeError:
print("An exception")
else:
print("successful")
输出:successful
23.元素频率(统计出现次数最多的元素)
def most_frequent(a):
return max(set(a),key=a.count)
print(most_frequent([1,2,2,2,3,3]))
输出:2
24.回文序列(会先将所有字母转换成小写字母,并且移除非英文字母符号)
def palindrome(string):
from re import sub
s=sub("[\W_]","",string.lower())
return s==s[::-1]
print(palindrome("taco cat"))
输出:True
25.不使用if else计算子
import operator
action={
"+":operator.add,
"-":operator.sub,
"*":operator.mul,
"/":operator.truediv,
"**":pow,
}
print(action["-"](50,25))
输出:25
26.Shuffle(打乱列表排序的顺序)
from copy import deepcopy
from random import randint
def shuffle(a):
tmp_list=deepcopy(a)
n=len(tmp_list)
while n:
n-=1
i=randint(0,n)
tmp_list[n],tmp_list[i]=tmp_list[i],tmp_list[n]
return tmp_list
print(shuffle([1,2,3]))
输出:[2,3,1](每次结果都不一样)
python小例子(一)的更多相关文章
- 这42个Python小例子,太走心
告别枯燥,60秒学会一个Python小例子.奔着此出发点,我在过去1个月,将平时经常使用的代码段换为小例子,分享出来后受到大家的喜欢. 一.基本操作 1 链式比较 i = 3print(1 < ...
- python小例子(三)
1.提高Python运行速度的方法 (1)使用生成器,节约大量内存: (2)循环代码优化,避免过多重复代码的执行: (3)核心模块使用cpython,pypy等: (4)多进程,多线程,协程: (5) ...
- python小例子(二)
1.在函数里面修改全局变量的值 2.合并两个字典.删除字典中的值 3.python2和python3 range(1000)的区别 python2返回列表,python3返回迭代器 4.什么样的语言可 ...
- Python小例子(判断质数)
只能被自己或者1整除的数为质数 num = int(input('请输入一个数:')) if num > 1: # 查看因子 for i in range(2, num): if (num % ...
- Python小例子(求和)
简单的数字的求和: a = input('请输入第一个数:') b = input('请输入第二个数:') sum = float(a) + float(b) print('数字{0}和数字{1}相加 ...
- Python小例子
import urllib.request as request import urllib.parse as parse import string print(""" ...
- [Spark][Hive][Python][SQL]Spark 读取Hive表的小例子
[Spark][Hive][Python][SQL]Spark 读取Hive表的小例子$ cat customers.txt 1 Ali us 2 Bsb ca 3 Carls mx $ hive h ...
- [Python]Python 使用 for 循环的小例子
[Python]Python 使用 for 循环的小例子: In [7]: for i in range(5): ...: print "xxxx" ...: print &quo ...
- [python]python 遍历一个list 的小例子:
[python]python 遍历一个list 的小例子: mlist=["aaa","bbb","ccc"]for ss in enume ...
随机推荐
- SPSS学习笔记参数检验—两配对样本t检验
目的:检验两个有联系的正态总体的均值是否存在显著差异. 适用条件:有联系,正态总体,样本量要一样.一般可以分为一下四种: ①同一受试对象处理前后的对比:如对于糖尿病人,对同一组病人在使用新治疗方法前测 ...
- win10下安装npm&cnpm步骤
1.node官网下载安装包 2.分别输入node -v,npm -v检查是否完成 3.配置npm的全局模块的存放路径以及cache的路径,新建node_global和node_cache文件,以下是我 ...
- MySQL 分页查询优化
有时在处理偏移量非常大的分页时候查询时,例如LIMIT 1000,10这样的查询,这时MySQL需要查询1010条记录然后只返回最后10条,前面1000条记录都被抛弃,这样的代价非常高.要优化这种查询 ...
- 在window里面安装ubuntu子系统并安装图形化界面
一.开启windows子系统 1. 在win10设置里面开启开发人员选项 (设置-->更新安全--> 开发者选项 )选择开启 2.在控制面板里面开启windows子系统 (启用或关闭wi ...
- 当我们在聊 Serverless 时你应该知道这些
作者 | 杨泽强(竹涧)阿里云技术专家 说起当前最火的技术,除了最新的区块链.AI,还有一个不得不提的概念是 Serverless.Serverless 作为一种新型的互联网架构,直接或间接推动了云计 ...
- 在Linux系统下有一个目录/usr/share/dict/ 这个目录里包含了一个词典的文本文件,我们可以利用这个文件来辨别单词是否为词典中的单词。
#!/bin/bash s=`cat /usr/share/dict/linux.words` for i in $s; do if [ $1 = $i ];then echo "$1 在字 ...
- latex转word公式 java (latextoword,latex_word,latex2word,latex_omml)
latex_word 主要目的: 给大家分享一个我的原创作品:latex转为word公式(omml)工具 [java] 此工具主要用于将含有latex公式的文本下载成word时,将latex转 ...
- Zookeeper学习笔记之 Zab协议(Zookeeper Atomic Broadcast)
Zab协议(Zookeeper Atomic Broadcast): 广播模式: Leader将所有更新(称为proposal),顺序发送给Follower 当Leader收到半数以上的Followe ...
- python程序设计基础(嵩天)第五章课后习题部分答案
第五章p1515.2:实现isodd()函数,参数为整数,如果参数为奇数,返回true,否则返回false.def isodd(s): x=eval(s) if(x%2==0): return Fal ...
- C# ManualResetEvent用法
ManualResetEvent表示线程同步事件,可以对所有进行等待的线程进行统一管理(收到信号时必须手动重置该事件) 其构造函数为: public ManualResetEvent (bool in ...