python笔记

bash 复制代码
1

any和all

Python any() 和 all() 函数

any() #只要有一个True,则返回True,全False才返回False

样例:判断字符串中是否有数字

python 复制代码
my_string = "coding**is**cool**345"
are_there_digits = [char.isdigit() for char in my_string]
print(any(are_there_digits))
# 输出True,其中有3 4 5都是数字,返回True;如果全不是数字,则返回False
True

all() #只要有一个False,则返回False,全True才返回True

样例:判断字符串中的所有字符是否都是字母

python 复制代码
my_string = "coding**is**cool"
are_all_letters = [char.isalpha() for char in my_string]
print(all(are_all_letters))
# Output 字符串中不全是字母,也有*,所以返回False;如果全是字母,则返回True
False

列表的enumerate()

python enumerate( )函数用法

enumerate(list, start=0) #返回下标和值,默认从0开始

python 复制代码
for index,value in enumerate(L, 1): #指定索引从1开始计数
    print(index, value)

文件的x模式

先判断文件是否存在,如果存在不覆盖写入,如果不存在,则w模式打开文件写入内容

python 复制代码
with open('onefile', 'xt') as f:
    f.write('abc\n')

带默认值的Dict

python中defaultdict用法详解

python 复制代码
from collections import defaultdict
dict = defaultdict(factory_function)

不是内置的函数,而是python标准库里的函数

defaultdict的作用是在于,当字典里的key不存在但被查找时,返回的不是keyError而是一个默认值,这个factory_function可以是list、set、str等等,作用是当key不存在时,返回的是工厂函数的默认值,比如list对应[ ],str对应的是空字符串

样例:可以统计字符串中出现数字的次数

python 复制代码
d = defaultdict(int)
for word in "123abc":
    d[word] += 1

# 输出 defaultdict(<class 'int'>, {'1': 1, '2': 1, '3': 1, 'a': 1, 'b': 1, 'c': 1})

样例:判断key是否存在,如果不存在,则新建一个list并赋值给key,如果已经存在,则调用list的append方法,将值添加进去

python 复制代码
d = defaultdict(list)
paris = {i:i*i for i in range(5)}
for k, v in paris.items():
    d[k].append(v)
# 输出 defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [4], 3: [9], 4: [16]})

有序的Dict

迭代时保留原始插入顺序

python 复制代码
from collections import OrderdDict

order_dict = OrderdDict(items=None)

python的Counter用法

样例:统计次数

python 复制代码
from collections import Counter
words_counts = Counter()
lines = "12332abcbc"
for word in lines:
    words_counts.update(word)
print("words_counts = ", words_counts)
# 输出 Counter({'2': 2, '3': 2, 'b': 2, 'c': 2, '1': 1, 'a': 1})

上下文管理器可以同时管理多个资源

__enter__协议

__exit__协议

python 复制代码
with open('data.txt') as data_r, open('target.txt', 'w') as tar_w:
    tar_w.write(date_r.read())

列表添加元素 append()和extend()区别

python 复制代码
names = ["Jimmy", "Timmy"]
more_names = ["Kenny", "Lenny"]
names.extend(more_names)
print(names)
# 输出['Jimmy', 'Timmy', 'Kenny', 'Lenny']

names = ["Jimmy", "Timmy"]
more_names = ["Kenny", "Lenny"]
names.append(more_names)
print(names)
# 输出['Jimmy', 'Timmy', ['Kenny', 'Lenny']]

列表动态删除元素

python 复制代码
def remove_list(lst,n):
    d = dict(zip(range(len(lst)), lst))
    return [v for k,v in d.items() if v != n]

进制转换

python 复制代码
bin(10) # 十进制转二进制
hex(1033) # 十进制转十六进制
int('10100111110',2)# 二进制到十进制

判断类型

  • str.isalnum():判断所有字符是否都是数字或者字母
  • str.isalpha():判断所有字符是否都是字母,不区分大小写
  • str.isdigit():判断所有字符是否都是数字
  • str.islower():判断字符串中所有字母是否都是小写
  • str.isupper():判断字符串中所有字母是否都是大写
  • str.istitle():判断字符串中所有单词的首字母都是大写
  • str.isspace():判断字符串中所有字符是否为由空白字符
  • str.isnumeric():判断所有字符是否都是数字(只针对 Unicode 对象)
  • str.isdecimal():判断所有字符是否都是十进制字符(只针对 Unicode 对象)
  • str.isidentifier():判断字符串是否为有效标识符
  • str.isprintable():判断字符串中所有字符是否都是可打印字符或字符串是否为空

分割字符串 正则表达式

python 复制代码
import re
# 大写字母分割字符串
re.findall('[A-Z][^A-Z]*', 'TheLongAndWindingRoad')
['The', 'Long', 'And', 'Winding', 'Road']
# 同样道理,数字分割字符串
tt = re.findall('[0-9][^0-9]*', '3SixOne4Thre6eOne7DoubleZ3e9ro')
['3SixOne', '4Thre', '6eOne', '7DoubleZ', '3e', '9ro']

分割字符串 partition

  • partition()方法用来根据指定的分隔符将字符串进行分割。
  • 字符串中包含多个分隔符,则以第一个来分割

如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。

python 复制代码
string = "Python is fun, isn't it"
print(string.partition('not '))
print(string.partition('is '))
# 输出
("Python is fun, isn't it", '', '') #分隔符不在字符串中
('Python ', 'is ', "fun, isn't it") #分隔符在字符串中

str和list转换和拼接

python 复制代码
# 字符串转换成列表
str1 = "12345"
list1 = list(str1)

str2 = "123 sjhid dhi"
list2 = str2.split() #or list2 = str2.split(" ")

# 列表转换成字符串 join拼接
str4 = "".join(list3)
str5 = ".".join(list3)

列出列表中所有长度为3的组合

python 复制代码
from itertools import combinations
print list(combinations([1,2,3,4,5], 3))
# 输出不重复的长度为3的组合
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]

zip函数

python3默认返回tuple的迭代器,不等长,以短的为准

python 复制代码
dict(zip(iterablesA, iterablesB)) #返回字典
list(zip(iterablesA, iterablesB)) #返回列表

样例:按照执行条件排序

python 复制代码
names = ['John', 'Amy', 'Jack'] scores = [98, 100, 85]
data = list(zip(names, scores)) data.sort()
按照姓名排序  [('Amy', 100), ('Jack', 85), ('John', 98)]

data = list(zip(scores, names)) data.sort()
按照分数排序  [(85, 'Jack'), (98, 'John'), (100, 'Amy')]

样例:求字符串数组中最长公共前缀

python 复制代码
strs = ["123abc123", "1234", "1256avb"]
for temp in zip(*strs):
    if len(set(temp)) == 1: #判断元祖各元素是否相等
        result += temp[0]
    else:
        break

isinstance接收一个元组

python 复制代码
isinstance(1, (float, int)) # True

排序时使用键(key)

python 复制代码
import operator
somelist = [(1, 5, 8), (6, 2, 4), (9, 7, 5)]
somelist.sort(key=operator.itemgetter(0))
#Output = [(1, 5, 8), (6, 2, 4), (9, 7, 5)] #根据第一个排序

somelist.sort(key=operator.itemgetter(1))
#Output = [(6, 2, 4), (1, 5, 8), (9, 7, 5)] #根据第二个排序

somelist.sort(key=operator.itemgetter(2))
#Output = [(6, 2, 4), (9, 7, 5), (1, 5, 8)] #根据第三个排序

一行代码启动http服务器

Windows平台上更快捷方便获取Linux服务器数据

bash 复制代码
python -m http.server 8082 #Linux终端启动
# win上浏览器打访问http://xx.xx.xx.xx:8082即可,xx是自己Linux机器的IP
相关推荐
蛋仔聊测试13 分钟前
Playwright 中 Page 对象的常用方法详解
python
码农101号20 分钟前
Linux中容器文件操作和数据卷使用以及目录挂载
linux·运维·服务器
前端付豪25 分钟前
17、自动化才是正义:用 Python 接管你的日常琐事
后端·python
jioulongzi26 分钟前
记录一次莫名奇妙的跨域502(badgateway)错误
开发语言·python
PanZonghui38 分钟前
Centos项目部署之Nginx 的安装与卸载
linux·nginx
PanZonghui44 分钟前
Centos项目部署之安装数据库MySQL8
linux·后端·mysql
PanZonghui1 小时前
Centos项目部署之运行SpringBoot打包后的jar文件
linux·spring boot
PanZonghui1 小时前
Centos项目部署之Java安装与配置
java·linux
破无差1 小时前
python实现简单的地图绘制与标记20250705
python
程序员弘羽1 小时前
Linux进程管理:从基础到实战
linux·运维·服务器