【Python】Python代码技巧

本文介绍了Python编程中的各种实用技巧,包括变量值交换、列表元素组合、查找频率最高值、字符串及列表反转、矩阵转置、字典合并、列表索引查找、字典键值对互换等,帮助读者提高编程效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.简洁的表达式

  • 交换变量值
a, b = 5, 10
print(a, b) # 5 10
a, b = b, a
print(a, b) # 10 5
  • 将列表中的所有元素组合成字符串
a = ['Python', 'is', 'awesome']
print(' '.join(a)) # Python is awesome
  • 查找列表中频率最高的值
a = [1, 2, 3, 1, 2, 3, 2, 2, 4, 5, 1]
print(max(set(a), key = a.count)) # 2


from collections import Counter

count = Counter(a)
print(count.most_common()) # [(2, 4), (1, 3), (3, 2), (4, 1), (5, 1)]
  • 检查两个字符串是不是由相同字母不同顺序组成
from collections import Counter

str1 = 'Hello Word'
str2 = 'Word Hello'
print(Counter(str1) == Counter(str2)) # True
  • 反转字符串及列表
a = 'abcdefghijklmnopqrstuvwxyz'
print(a[::-1]) # zyxwvutsrqponmlkjihgfedcba

a = [1, 2, 3, 4, 5]
print(a[::-1]) # [5, 4, 3, 2, 1]
  • 转置矩阵
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = zip(*matrix)
print(list(transposed)) # [(1, 4), (2, 5), (3, 6)]
  • 合并字典
d1 = {'a':1}
d2 = {'b':2}

print({**d1, **d2}) # {'a': 1, 'b': 2}
print(dict(d1.items() | d2.items())) # {'a': 1, 'b': 2}

d1.update(d2)
print(d1) # {'a': 1, 'b': 2}
  • 列表中最小和最大值的索引
lst = [40, 10, 20, 30]

def minIndex(lst):
	return min(range(len(lst)), key=lst.__getitem__)

def maxIndex(lst):
	return max(range(len(lst)), key=lst.__getitem__)


print(minIndex(lst)) # 1
print(maxIndex(lst)) # 0

  

  • zip 函数实现字典键值对互换
lang = {'python':'.py', 'java':'.java'}
lang = dict(zip(lang.values(), lang.keys()))
print(lang) # {'.py': 'python', '.java': 'java'}
  • isinstance 函数可用于判断实例的类型,其实它的第二个参数可以是多个数据类型组成的元组
isinstance(x, (int, str))

# 等价于

isinstance(x, int) or isinstance(x, float)


# 类似的函数还有字符串的 startswith 方法和 endswith 方法

s.startswith(('"""', "'''"))

# 等价于

s.startswith("'''") or s.startswith('"""')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值