常用编程技巧(Python篇)
输入输出
输入一个整数 n,再输入 n 个数
n = int(input())
stu = list(map(int, input().split()))
数组操作
判断数组是否为空
if not stu:
统计数组中某个元素出现的次数
v_max_size = stu.count(v_max)
数组逆序遍历
arr = [1, 2, 3, 4, 5]
for i in range(len(arr) - 1, -1, -1): # 起始值(包含),终止值(不包含),步长
print(arr[i])
数组元素转为字符串
index_str = ",".join(str(i) for i in index) # 输出类似: 3,0,4,3,1,0
使用 reverse() 原地反转数组
arr.reverse()
字符串处理
去除首尾空白并分割字符串为数组
input().strip().split()
小数格式化输出
方法一:format() 函数
price = 12.3456
print("价格是 {:.2f}".format(price)) # 输出: 价格是 12.35
方法二:f-string(推荐,Python 3.6+)
print(f"价格是 {price:.2f}") # 输出: 价格是 12.35
方法三:round() 函数
print(round(price, 2)) # 输出: 12.35
⚠️ 注意:
round()返回 float,若需格式化输出建议使用 f-string。
遍历技巧
不使用循环变量时使用 _
for _ in range(n):
第一次循环单独处理(标志位法)
arr_str = ""
first_time = True
for indexs in index:
if first_time:
arr_str = str(indexs)
first_time = False
else:
arr_str += "," + str(indexs)
Python 字典操作
从键盘输入单词并统计词频
from collections import defaultdict
def main():
word_count = defaultdict(int) #默认初始化一个带值的字典
print("Enter words (Ctrl+D or Ctrl+Z to end):")
try:
while True:
line = input().strip()
if not line:
continue
words = line.split()
for word in words:
word_count[word] += 1
except EOFError:
pass
for word,count in sorted(word_count.items()):
print(f"{word}: {count}")
if __name__ == "__main__":
main()
初始化字典并统计词频
text = "apple banana apple orange banana apple"
words = text.split()
freq = {}
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
print(freq)
# 输出: {'apple': 3, 'banana': 2, 'orange': 1}
声明字典
dict = {1: "星期一", 2: "星期二"}
map() 函数用法
map(function, iterable)
将函数应用于可迭代对象的每个元素。结果是一个迭代器(懒加载),可用 list() 获取全部结果。
示例:所有元素乘 2
nums = [1, 2, 3, 4]
result = map(lambda x: x * 2, nums)
print(list(result)) # 输出: [2, 4, 6, 8]
快速将输入的字符串转为整数数组
list(map(int, input().split()))
同时输入两个数并赋值
a, b = map(int, input("请输入两个数,用空格隔开:").split())

浙公网安备 33010602011771号