Python 常用命令(一)

一、内置函数

字符串相关(数)

需求 输入 输出
计算字符串长度 len(“Hello, Python!”) 14
str1 = ‘aaBBccEEff’ 统计字符串中指定字符出现的次数(指定范围) str1.count(“a”, 0, 3) 2
查找字符串中指定的字符第一次出现的索引(指定范围),不会触发异常(返回-1) str1.find(“d”, 3) -1
查找~,会触发异常 str1.index(“c”, 3) 4
二进制 → 十进制 int(‘101010’,2) 42
八进制 → 十进制 int(‘367’,8) 247
十六进制 → 十进制 int(‘FFF’,16) 4095

字符串相关(字符型)

需求 输入 输出
str1 = ‘aaBBccEEff’ 全部转换为小写字符 str1.lower() ‘aabbcceeff’
全部转换为大写字符 str1.upper() ‘AABBCCEEFF’
将字符串中的字符替换为指定的字符 str1.replace(“a”, “W”, 1) ‘WaBBccEEff’
test1 = “ abc “删除字符串两边的所有空白 test1.strip() ‘abc’
删除字符串指定字符 test1.strip().strip(“a”) ‘bc’

字符串相关(布尔型)

需求 输入 输出
判断字符串是否以指定字符开头(指定范围) str1.startswith(“a”) True
判断字符串是否以指定字符结尾(指定范围) str1.endswith(“b”, 0, 2) False
input_str = ‘123’ 识别整数 input_str.isdigit() True
识别字母 input_str.isalpha() False
识别字母和数字 input_str.isalnum() True
识别空白字符 input_str.isspace() False
input_str = ‘hello’ 识别小写字母 input_str.islower() True
识别大写字母 input_str.isupper() False
识别字符串是否以指定前缀开头 input_str.startswith(‘he’) True
识别字符串是否以指定后缀结尾 input_str.endswith(‘lo’) False

数字相关

需求 输入 输出
绝对值 abs(-5) 5
商和余数 divmod(13,2) (6,1)
四舍六入五看齐,奇进偶不进 round(3.50) 4
求 a 的 b 次幂(取余) pow(5,2) , pow(5,2,3) (25, 1)
求和 sum([1,2,3,4,5,6,7,8,9,10]) 55
求最小值 min(3,2,5,19,6,3) 2
求最大值 max(3,5,12,8,5,11) 12
创建不可变的数字序列 list(range(1, 10, 2) [1, 3, 5, 7, 9]
十进制 → 二进制,八进制,十六进制 bin(10), oct(10), hex(10) 0b1010, ‘0o12’, ‘0xa’
返回一个Unicode编码的整数对应的字符 chr(65) ‘A’
创建一个复数 complex(3,4) (3+4j)
保留一位小数 round(3.14159, 1) 3.1

列表相关

需求 输入 输出
iterable=[True, True, False] 可迭代对象中所有元素是否为真 all(iterable) False
iterable = [False, False, True] 可迭代对象中有元素是否为真 any(iterable) True
iterable = [1, 2, 3] sum(iterable) 6
numbers = [1, 2, 3],letters = [‘a’, ‘b’, ‘c’] 打包 zip(numbers, letters) [(1, ‘a’), (2, ‘b’), (3, ‘c’)]

二、单行命令

生成等差数列

生成一个从1到10的等差数列,公差为1。放入列表list1中。

1
2
list1 = [i for i in range(1, 11, 1)]
print(list1)

输出结果[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

反转字符串

切片操作符[::-1]。从后向前取值,步长为-1,即实现字符串反转。

1
2
str1 = "Hello, World!"
print(str1[::-1])

输出结果!dlroW ,olleH

列表去重

使用set()函数将列表转换为集合,自动去除重复元素,再将其转换回列表。

1
2
3
list2 = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(list2))
print(unique_list)

输出结果[1, 2, 3, 4, 5]

简洁计算阶乘

当n等于0时,阶乘为1;否则,阶乘等于n乘以n-1的阶乘。此处递归未定义函数,实际应用中需确保递归深度可控。

1
2
factorial = lambda n:1 if n == 0 else n * factorial(n - 1)
print(factorial(5))

输出结果120

统计字符串中单词出现次数

str.count()方法用于统计字符串中指定子串(在此例中为’hello’)出现的次数

1
2
3
text = "hello world hello python"
word_count = text.count('hello')
print(word_count)

输出结果2

生成斐波那契数列

使用列表推导式结合append()函数生成斐波那契数列。fibonacci初始为[0, 1],接着逐次计算前两项之和,不断扩展列表。

1
2
3
fibonacci = [0, 1]
[fibonacci.append(fibonacci[i] + fibonacci[i+1]) for i in range(10)]
print(fibonacci)

输出结果[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

快速交换两个变量值

Python允许同时赋值多个变量

1
2
3
a, b = 10, 20
a, b = b, a
print(a, b)

输出结果20 10

求最大公约数(GCD)

Python内置math模块中的gcd()函数,直接计算两个数的最大公约数。

1
2
3
import math
gcd = math.gcd(48, 18)
print(gcd)

输出结果6

列表元素排序并保持原索引

使用sorted()函数对列表索引进行排序,key参数指定按照my_list对应位置的元素值进行排序。这样,原列表的元素顺序不变,但索引已按元素值排序。

1
2
3
my_list = [ 'elderberry','apple', 'banana', 'cherry', 'date',]
sorted_list = sorted(range(len(my_list)), key=lambda i: my_list[i])
print(sorted_list)

输出结果[1, 2, 3, 4, 0]

使用列表推导式高效生成新列表

列表推导式可以简洁地根据现有列表numbers生成一个新的列表squared

1
2
3
numbers = [1, 2, 3, 4, 5]
squared = [num **2 for num in numbers]
print(squared)

输出结果[1, 4, 9, 16, 25]

矩阵转置

zip()函数将矩阵的行转为列,再使用map()和list()将结果转换为列表形式

1
2
3
matrix = [[1, 2], [3, 4], [5, 6]]
transposed = list(map(list, zip(*matrix)))
print(transposed)

输出结果[[1, 3, 5], [2, 4, 6]]

快速判断素数

检查n是否能被2到其平方根之间的任何数整除。如果都不能整除,则返回True,表示n是素数。

1
2
3
4
def is_prime(n):
return all(n % i != 0 for i in range(2, int(n**0.5)+1))

print(is_prime(17))

输出结果True

快速组合

使用itertools.product()函数生成多个列表的笛卡尔积,结果为一个包含所有组合的列表。

1
2
3
import itertools
cartesian_product = list(itertools.product(['A','B',"C"], ["a","b","c"],[1,2,3]))
print(cartesian_product)

输出结果[('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3), ('A', 'b', 1), ('A', 'b', 2), ('A', 'b', 3), ('A', 'c', 1), ('A', 'c', 2), ('A', 'c', 3), ('B', 'a', 1), ('B', 'a', 2), ('B', 'a', 3), ('B', 'b', 1), ('B', 'b', 2), ('B', 'b', 3), ('B', 'c', 1), ('B', 'c', 2), ('B', 'c', 3), ('C', 'a', 1), ('C', 'a', 2), ('C', 'a', 3), ('C', 'b', 1), ('C', 'b', 2), ('C', 'b', 3), ('C', 'c', 1), ('C', 'c', 2), ('C', 'c', 3)]

遍历列表并打印索引和对应的值

使用 enumerate() 函数遍历列表并打印索引和对应的值, 创建生成器对象

1
2
3
4
5
6
generator = ((i, j) for i, j in enumerate(['A', 'B', 'C']))
# 方法一
for item in generator:
print(item)
# 方法二
print(list(((i, j) for i, j in enumerate(['A', 'B', 'C']))))

输出结果(0, 'A') (1, 'B') (2, 'C') or [(0, 'A'), (1, 'B'), (2, 'C')]

对列表中元素排序

对可迭代对象做排序操作

1
2
3
4
5
6
7
8
9
10
# 方法一
lst = [5,7,6,12,1,13,9,18,5]
lst.sort()
print(lst)

# 方法二
print(sorted(lst))

#倒序
sorted(lst,reverse=True)

输出结果[1, 5, 5, 6, 7, 9, 12, 13, 18]

将对象中对应的元素打包成一个元组

将可迭代的对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回的列表长度与最短的对象相同。

1
2
3
4
5
6
lst1 = ['a', 'b', 'c', 'd', 'e', 'f']
lst2 = ['1', '2', '3', '4', '5', '6']
lst3 = ['one', 'two', 'three', 'four', 'five', 'six']

for el in zip(lst1, lst2, lst3):
print(el)

输出结果('a', '1', 'one') ('b', '2', 'two') ('c', '3', 'three') ('d', '4', 'four') ('e', '5', 'five') ('f', '6', 'six')

python内置进制转换

1
2
3
4
5
6
7
8
9
10
11
dec = input('10进制数为:')
print("转换为二进制为:", bin(dec))
print("转换为八进制为:", oct(dec))
print("转换为十六进制为:", hex(dec))

string1 = '101010'
print('二进制字符串转换成十进制数为:'int(string1,2))
string1 = '367'
print('八进制字符串转换成十进制数为:'int(string1,8))
string3 = 'FFF'
print('十六进制字符串转换成十进制数为:'int(string1,16))

求质数

求质数的几种境界

求质因数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def is_prime(n):
return all(n%i !=0 for i in range(2,int(n**0.5)+1))

def get_primes(n):
prime_list =[]
while not is_prime(n):
for j in range(2,int(n**0.5)+1):
if is_prime(j) and n%j ==0:
prime_list.append(j)
n = int(n/j)
prime_list.append(n)

return prime_list


num = int(input())
prime_list_out = get_primes(num)
prime_list_out.sort()
formatted_output = ' '.join(map(str, prime_list_out))


print(formatted_output)

map 对可迭代对象中的每个元素应用一个函数

int,str等函数都可以作为 map 的函数

1
2
3
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers))

filter 函数根据条件筛选

1
2
3
numbers = [1, 2, 3, 4, 5, 6]
filtered_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(filtered_numbers))

参考资料:

  1. https://mp.weixin.qq.com/s/1g92Sr3WtB67XEiFrCv8oQ
  2. https://mp.weixin.qq.com/s/IOFMUH5rIfUF0GhNpsenlg
  3. https://mp.weixin.qq.com/s/OmTFXbwIOATSHIOJK1CVkQ