20个值得学习的 Python 技巧
python教程
共 3591字,需浏览 8分钟
·
2020-12-05 20:39
str1="qwert"
rev_str1=str1[::-1]
#输出
# trewq
str1="this is a book"
print(str1.title())
# This Is A Book
str1="aabbccccdddd"
set1=set(str1)
new_str=''.join(set1)
print(new_str)
i=4
str1="abcd"
list1=[1,2]
print(str1*i)
# abcdabcdabcdabcd
print(list1*i)
# [1,2,1,2,1,2,1,2]
list1=[1,2,3]
new_list1=[2*i for i in list1]
# [2,4,6]
x=1
y=2
x,y=y,x
print(x) # 2
print(y) # 1
str1="This is a book"
str2="test/ str 2"
print(str1.split()) # ['This', 'is', 'a', 'book']
print(str2.split('/')) # ['test', ' str 2']
list_str=['This','is','a','book']
print(','.join(list_str))
# This,is,a,book
str1="qqaabb"
if str1==str1[::-1]:
print("回文")
else:
print("不是")
# 不是
from collections import Counter
list1=['a','b','a','c','c','c']
count=Counter(list1)
print(count)
print(count['b'])
print(count.most_common(1))
s1,s2,s3="acbde","abced","abcda"
c1,c2,c3=Counter(s1),Counter(s2),Counter(s3)
if c1==c2:
print('1和2是异序词')
if c1==c3:
print('1和3是异序词')
a,b=1,0
try:
print(a/b)
# b为0的时候触发异常
except ZeroDivisionError:
print("除数为0")
else:
print("不存在异常")
finally:
print("此段总是会执行")
list1=['a','b','c','d','e']
for idx,val in enumerate(list1):
print('{0}:{1}'.format(idx,val))
# 0:a
# 1:b
# 2:c
# 3:d
# 4:e
import sys
num=21
print(sys.getsizeof(num))
dic1={'app':9,'banana':6}
dic2={'banana':4,'orange':8}
com_dict={**dic1,**dic2}
# {'apple':9,'banana':4,'orange':8}
import time
s_time=time.time()
a,b=1,2
c=a+b
e_time=time.time()
time_taken_in_micro=(e_time-stime)*(10**6)
print("程序运行的毫秒:{0} ms".format(time_taken_in_micro))
from iteration_utilities import deepflatten
# 如果嵌套列表的深度只有1层
def flatten(l):
return [item for sublist in l for item in sublist]
l=[[1,2,3],[3]]
print(flatten(l))
# [1,2,3,3]
# 如果不知道列表嵌套深度
l=[[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
print(list(deepflatten(l,depth=3)))
# [1,2,3,4,5,6,7,8,9,10]
import random
list1=['a','b','c','d','e']
ns=2
samples=random.sample(list1,ns)
print(samples)
# ['a','c']
import secrets
s_rand=secrets.SystemRanom()
list1=['a','b','c','d','e']
ns=2
samples=s_rand.sample(list1,ns)
print(samples)
# ['c','d']
nums=123456
# 使用map
digit_list=list(map(int,str(nums)))
print(digit_list)
# [1,2,3,4,5,6]
# 使用列表表达式
digit_list=[int(x) for x in str(nums)]
print(digit_list)
# [1,2,3,4,5,6]
def unique(l): if len(l)==len(set(l)): print("所有元素是唯一的") else: prin
欢迎大家点赞,留言,转发,转载,感谢大家的相伴与支持
万水千山总是情,点个【在看】行不行
*声明:本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜
评论