Python-操作笔记

Python-操作笔记

  1. 交换变量
# 交换变量
a, b = 1, 2
print(a, b)
a, b = b, a
print(a, b)

配图
2. 合并列表中的所有元素

# 组合字符串
a = ["Hallo","World","!!","fish"]
print(" ".join(a))

pt

join()函数语法: ‘sep’.join(a)
返回值:返回一个以分隔符sep连接列表a各个元素后生成的字符串
列表a 必须为字符数组

  1. 找到列表中词频最高的元素
# 频率最高的值
# 方法A
a = [1,2,3,1,1,1,2,1,2,3,4,5,1]
print(max(set(a), key = a.count))
# 方法B
from collections import Counter
cnt = Counter(a)
print(cnt.most_common(3))

Counter.most_common(n) :
计数:n代表取前n个计数最大的元素
set(a) 移除a中重复元素

pt

  1. 检查两个字符串是不是由相同字母不同顺序组成
from collections import Counter
a = "HalloWorld"
b = "dlroWollaH"
print(Counter(a))
print(Counter(a)==Counter(b))

pt

  1. 反转字符串
# 反转 列表/字符串/数值
# A
a = "HalloWorld"
print(a[::-1])
# B
for char in reversed(a):
    print(char)
# C
num = 20200810
print(int(str(num)[::-1]))

pt

  1. 转置
# 转置
a = [
    ["a", "d"],
    ["b", "e"],
    ["c", "f"],
]
t = zip(*a)
print(list(t))

pt
Python zip 和 * 的使用方法

  1. 复制
# copy
a = "HalloWorld!"
b = a

c = list(a).copy()

import copy
d = copy.deepcopy(a)

print(a)
print(b)
print(c)
print(d)

pt

  1. 通过键排序字典元素
d = {
    
    'xiaoming':24, 'xiaohong':27, 'fish':22}
print(sorted(d.items(), key=lambda x:x[1]))

from operator import itemgetter
print(sorted(d.items(), key=itemgetter(1)))

print(sorted(d,key=d.get))

key=lambda x: x[1] 为对前面的对象中的第二维数据(即value)的值进行排序。
key=lambda 变量:变量[维数] 。
同理:key=itemgetter(1) [维数]

pt

扫描二维码关注公众号,回复: 12679256 查看本文章
  1. 合并字典
#合并字典
d1 = {
    
    'xiaoming':24, 'xiaohong':27, 'fish':22}
d2 = {
    
    'xiaoxin':32, 'xiaotong':21, 'peiyu':23}

print({
    
    **d1, **d2})

print(dict(d1.items()|d2.items()))

d1.update(d2)
print(d1)

pt

  1. 列表推导式
    转:Python的各种推导式(列表推导式、字典推导式、集合推导式)

  2. 大写首字母

s = "hallo,fish."
print(s.title())

pt
12. 分块

from math import ceil
def chunk(lst, size):
    return list(map(lambda x: lst[x * size:x * size + size],list(range(0, ceil(len(lst) / size)))))
print(chunk([1,2,3,4,5],2))

pt
13. 查看执行时间

import time
start_time = time.time()
a = 1
b = 2
c = a + b
print(c) #3
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)

pt
14. try、except、else

try:
    2*3 #没出错是这里
except TypeError:
    print("出错就执行这里")
else:
    print("这里无论如何都会执行.")

pt

猜你喜欢

转载自blog.csdn.net/weixin_41809530/article/details/107905715