Python 语言基础

Python 区分大小写,代码块由缩进表示,通常使用四个空格。序列下标默认从 0 开始;range 和切片均采用左闭右开的范围。竞赛中除语法正确外,还应关注输入输出和算法复杂度。

1. 导入、变量与类型转换

import math
from math import gcd

text = "101"
n = int(text)
ratio = float("3.5")
ch = chr(65)
code = ord("A")

使用 import math 后以 math.sqrt(x) 调用模块成员;也可用 from math import gcd 导入指定函数。常见类型有 intfloatstrbool,可用 type(x) 查看类型,并通过 int()float()str() 转换。变量名应具有含义,避免覆盖 liststrdict 等内建名称。

2. 运算与流程控制

算术运算符包括 + - * / // % **/ 为真除法,// 为整除,** 为幂。比较运算有 == != < <= > >=;逻辑运算为 notandor;位运算为 ~ & | ^ << >>in 判断成员关系,is 判断对象身份,二者不可混用。

answer = 0
for x in range(1, n + 1):
    if x % 2 == 0:
        answer += x
    elif x < 0:
        continue

while answer > 100:
    answer -= 100

if / elif / else 用于分支,while 在条件成立时循环,for 适合遍历序列或 range(start, stop, step)break 立即退出当前循环,continue 跳过当前轮。

3. 常用容器与切片

容器特点常见用途
list有序、可变动态数组;尾部 append 均摊 O(1)。
tuple有序、不可变固定记录、函数返回多个值。
str有序、不可变文本处理、splitjoin
dict键值映射计数、索引;查找平均 O(1)。
set不重复元素集合去重、成员查询平均 O(1)。
a = [10, 20, 30, 40, 50]
first, last = a[0], a[-1]
middle = a[1:4]
reversed_a = a[::-1]

freq = {}
for x in a:
    freq[x] = freq.get(x, 0) + 1

seen = set(a)

切片 a[start:end:step] 会创建新序列,处理大数据时不可滥用。列表按下标访问为 O(1),中间插入、删除和 pop(0) 通常为 O(n)。字典用 get(key, default) 可避免不存在键时的 KeyError;遍历键值对可用 for key, value in d.items()

4. 字符串、函数与排序

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

text = "10 20 30"
nums = list(map(int, text.split()))
message = ",".join([str(x) for x in nums])

pairs = [(2, "b"), (1, "a")]
pairs.sort(key=lambda item: item[0])

函数用 def 定义,return 返回结果;可变对象传入函数后,函数内的原地修改会影响调用方。字符串不可变,频繁拼接长字符串会产生额外开销,应先收集片段再用 ''.join(parts)sorted(a) 返回新列表,a.sort() 原地排序且返回 None,二者通常为 O(n log n)

5. 竞赛输入与复杂度意识

import sys

input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
print(sum(a))

输入量较大时可将 input 绑定为 sys.stdin.readline。常用内建函数包括 lensumminmaxenumeratezipmath 模块提供 gcdsqrt 等数学函数。选择容器和写法时要避免在循环中重复切片、重复排序或执行线性队首删除。