📚Day1: 输入输出 + 类型转换 知识点完全总结
1. 输入输出
python
python
# 输入
name = input() # 读取一行字符串
age = int(input()) # 读取整数
# 输出
print("Hello", name) # 空格分隔
print(f"Age: {age}") # f-string格式化
print("%s is %d" % (name, age)) # %格式化
2. 类型转换
python
python
int("123") # 字符串转整数
float("3.14") # 字符串转浮点数
str(100) # 数字转字符串
hex(255) # 转十六进制 '0xff'
- 进度转化的内置函数
python
# 十六进制 → 十进制
int('1A3', 16) # 419
# 十进制 → 十六进制hexadecimal
hex(419) # '0x1a3'
# 二进制 → 十进制
int('1010', 2) # 10
# 十进制 → 二进制binary
bin(10) # '0b1010'
# 八进制 → 十进制
int('12', 8) # 10
# 十进制 → 八进制octal
oct(10) # '0o12'
- 类型转化的内置函数
python
# 数字字符 → 整数
int('9') # 9
# 字母 → ASCII码
ord('A') # 65
ord('F') # 70
# ASCII码 → 字母
chr(65) # 'A'
# 利用ASCII计算(A-F对应10-15)
ord('A') - ord('A') + 10 # 10
ord('F') - ord('A') + 10 # 15
二、现在测试理解(回答问题,不要写代码)
问题1: 如果用户输入 "3.14",你想把它转成整数,应该怎么做?可以直接 int("3.14") 吗?
写round(float("3.14")),不可以因为原本是字符串类型,转化的情况不同
问题2: print(1, 2, 3) 和 print("1", "2", "3") 的输出有什么区别?
一个输出的是数字,另外一个是字符
问题3: 如何让小数只保留2位输出?(提示:格式化方法有哪些?)
直接%.2f
python
num = 3.1415926
# 方法1:%格式化(你说的)
print("%.2f" % num) # 输出: 3.14
# 方法2:format()方法
print("{:.2f}".format(num)) # 输出: 3.14
# 方法3:f-string(Python 3.6+,最推荐)
print(f"{num:.2f}") # 输出: 3.14
一、输入输出完全指南
1. 输入(input)的各种情况
基础输入
python
# 单行字符串输入
name = input() # 读取一行,返回字符串
# 单行整数输入
age = int(input()) # 先读字符串,再转int
# 单行浮点数输入
score = float(input()) # 先读字符串,再转float
多个数据一行输入(重点!)⭐
python
# 输入:10 20 30
# 方法1:split() + 列表推导式(推荐)
nums = [int(x) for x in input().split()]
# nums = [10, 20, 30]
# 方法2:split() + map()
nums = list(map(int, input().split()))
# nums = [10, 20, 30]
# 方法3:解包赋值(数量确定时)
a, b, c = map(int, input().split())
# a=10, b=20, c=30
多行输入(常见题型)⭐⭐⭐
情况1:已知行数
python
# 已知要读3行
lines = []
for i in range(3):
line = input()
lines.append(line)
情况2:第一行是数量 n,后面 n 行数据
python
# 输入:
# 3
# apple
# banana
# orange
n = int(input())
fruits = []
for i in range(n):
fruit = input()
fruits.append(fruit)
情况3:未知行数(读到EOF)⭐⭐⭐
python
# 牛客最常见!读取直到没有输入
# 方法1:try-except(推荐)
while True:
try:
line = input()
# 处理line
except EOFError:
break
# 方法2:sys.stdin(效率更高)
import sys
for line in sys.stdin:
line = line.strip() # 去除末尾换行符
# 处理line
2. 输出(print)格式化详解 ⭐⭐⭐
A. 基础输出
python
print("Hello") # Hello
print(123) # 123
print(3.14) # 3.14
B. 多个值输出(控制分隔符)⭐⭐⭐
python
# 默认用空格分隔
print(1, 2, 3) # 输出:1 2 3
# 自定义分隔符 sep
print(1, 2, 3, sep=',') # 输出:1,2,3
print(1, 2, 3, sep='-') # 输出:1-2-3
print(1, 2, 3, sep='') # 输出:123
# 控制结尾 end(默认是换行)
print("Hello", end='') # 不换行
print("World") # 输出:HelloWorld
print("A", end=' ')
print("B") # 输出:A B
牛客常见坑:题目要求空格分隔还是逗号分隔?
python
# 要求:1 2 3(空格分隔)
print(*nums) # 推荐!自动展开列表
# 或
print(' '.join(map(str, nums)))
# 要求:1,2,3(逗号分隔)
print(','.join(map(str, nums)))
C. 格式化输出(重点!)⭐⭐⭐
方法1:% 格式化(经典)
python
name = "Alice"
age = 20
score = 95.678
# 字符串:%s
print("Name: %s" % name) # Name: Alice
# 整数:%d
print("Age: %d" % age) # Age: 20
# 浮点数:%f(默认6位小数)
print("Score: %f" % score) # Score: 95.678000
# 浮点数:%.2f(保留2位小数)⭐
print("Score: %.2f" % score) # Score: 95.68
# 多个值
print("%s is %d years old" % (name, age))
# Alice is 20 years old
常用格式符:
python
%s 字符串
%d 整数
%f 浮点数(默认6位小数)
%.2f 浮点数(保留2位小数)
%.0f 浮点数(保留0位小数,四舍五入)
%x 十六进制(小写)
%X 十六进制(大写)
%o 八进制
方法2:format() 方法
python
name = "Bob"
age = 25
score = 88.456
# 基础用法
print("Name: {}".format(name)) # Name: Bob
# 位置参数
print("{} is {} years old".format(name, age))
# Bob is 25 years old
# 索引指定
print("{0} is {1}, {0} again".format(name, age))
# Bob is 25, Bob again
# 保留小数 ⭐
print("Score: {:.2f}".format(score)) # Score: 88.46
# 指定宽度(右对齐)
print("Score: {:10.2f}".format(score)) # Score: 88.46
# ^^^^空格填充
# 左对齐
print("Score: {:<10.2f}".format(score)) # Score: 88.46
# 居中对齐
print("Score: {:^10.2f}".format(score)) # Score: 88.46
方法3:f-string(Python 3.6+,最推荐!)⭐⭐⭐
python
name = "Charlie"
age = 30
score = 92.345
# 基础用法
print(f"Name: {name}") # Name: Charlie
print(f"{name} is {age} years old") # Charlie is 30 years old
# 表达式计算
print(f"Next year: {age + 1}") # Next year: 31
# 保留小数 ⭐
print(f"Score: {score:.2f}") # Score: 92.35
# 宽度和对齐
print(f"Score: {score:10.2f}") # Score: 92.35
print(f"Score: {score:<10.2f}") # Score: 92.35
print(f"Score: {score:^10.2f}") # Score: 92.35
# 进制转换
num = 255
print(f"Hex: {num:x}") # Hex: ff
print(f"Hex: {num:X}") # Hex: FF
print(f"Oct: {num:o}") # Oct: 377
print(f"Bin: {num:b}") # Bin: 11111111
D. 格式化对比表(速查)⭐⭐⭐
E. 常见输出格式问题总结 ⭐⭐⭐
问题1:多个数用空格分隔
python
nums = [1, 2, 3, 4, 5]
# ❌ 错误
print(nums) # [1, 2, 3, 4, 5] 带方括号!
# ✅ 正确方法1(推荐)
print(*nums) # 1 2 3 4 5
# ✅ 正确方法2
print(' '.join(map(str, nums))) # 1 2 3 4 5
问题2:输出不换行
python
# 题目要求:在同一行输出多次
# ❌ 错误
for i in range(5):
print(i) # 每个数字一行
# ✅ 正确
for i in range(5):
print(i, end=' ') # 0 1 2 3 4
问题3:小数保留位数
python
num = 3.1415926
# 要求保留2位小数
print(f"{num:.2f}") # 3.14
print("%.2f" % num) # 3.14
print("{:.2f}".format(num)) # 3.14
# 要求保留0位(四舍五入到整数)
print(f"{num:.0f}") # 3
问题4:整数宽度补零
python
num = 5
# 要求:输出 005(宽度为3,前面补0)
print(f"{num:03d}") # 005
print("%03d" % num) # 005
print("{:03d}".format(num)) # 005
问题5:输出多行的格式
python
# 题目要求每个结果占一行
results = [10, 20, 30]
# ✅ 方法1
for r in results:
print(r)
# ✅ 方法2
print('\n'.join(map(str, results)))
二、类型转换完全指南
1. 基础类型转换
python
# 字符串 → 整数
int("123") # 123
int("3.14") # ❌ ValueError!
# 字符串 → 浮点数
float("3.14") # 3.14
float("123") # 123.0
# 浮点数 → 整数(截断小数)
int(3.9) # 3(直接截断)
int(-3.9) # -3
# 四舍五入
round(3.5) # 4
round(3.14159, 2) # 3.14(保留2位)
# 整数/浮点数 → 字符串
str(123) # "123"
str(3.14) # "3.14"
2. 进制转换 ⭐⭐⭐
其他进制 → 十进制
python
# 二进制字符串 → 十进制
int("1010", 2) # 10
# 八进制字符串 → 十进制
int("12", 8) # 10
# 十六进制字符串 → 十进制
int("A", 16) # 10
int("FF", 16) # 255
十进制 → 其他进制
python
num = 255
# 十进制 → 二进制字符串
bin(num) # '0b11111111'
bin(num)[2:] # '11111111'(去掉0b前缀)
# 十进制 → 八进制字符串
oct(num) # '0o377'
oct(num)[2:] # '377'
# 十进制 → 十六进制字符串
hex(num) # '0xff'
hex(num)[2:] # 'ff'
hex(num)[2:].upper() # 'FF'(大写)
手动实现进制转换(面试常考)⭐⭐⭐
十进制 → 其他进制(短除法)
python
def dec_to_bin(n):
"""十进制转二进制"""
if n == 0:
return "0"
result = ""
while n > 0:
result = str(n % 2) + result # 余数放前面
n = n // 2
return result
print(dec_to_bin(10)) # "1010"
# 十六进制同理
def dec_to_hex(n):
if n == 0:
return "0"
hex_chars = "0123456789ABCDEF"
result = ""
while n > 0:
result = hex_chars[n % 16] + result
n = n // 16
return result
print(dec_to_hex(255)) # "FF"
其他进制 → 十进制(按权展开)
python
def bin_to_dec(s):
"""二进制字符串转十进制"""
result = 0
for i, char in enumerate(reversed(s)):
result += int(char) * (2 ** i)
return result
print(bin_to_dec("1010")) # 10
def hex_to_dec(s):
"""十六进制字符串转十进制"""
hex_map = {
'0':0, '1':1, '2':2, '3':3, '4':4,
'5':5, '6':6, '7':7, '8':8, '9':9,
'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15
}
result = 0
for i, char in enumerate(reversed(s)):
result += hex_map[char.upper()] * (16 ** i)
return result
print(hex_to_dec("FF")) # 255
3. 字符与ASCII码转换
python
# 字符 → ASCII码
ord('A') # 65
ord('a') # 97
ord('0') # 48
# ASCII码 → 字符
chr(65) # 'A'
chr(97) # 'a'
chr(48) # '0'
# 利用ASCII实现大小写转换
char = 'a'
upper_char = chr(ord(char) - 32) # 'A'
# 当然,实际用 char.upper() 更简单
4. 字符串与列表转换
python
# 字符串 → 列表
s = "hello"
list(s) # ['h', 'e', 'l', 'l', 'o']
# 字符串按分隔符拆分
s = "1 2 3"
s.split() # ['1', '2', '3']
s.split(',') # 按逗号分隔
# 列表 → 字符串
chars = ['h', 'e', 'l', 'l', 'o']
''.join(chars) # "hello"
nums = [1, 2, 3]
' '.join(map(str, nums)) # "1 2 3"
三、牛客题目常见套路总结 ⭐⭐⭐
套路1:多组测试用例(最常见!)
python
# 题目:输入若干行数据,每行处理后输出
while True:
try:
line = input()
# 处理并输出
result = process(line)
print(result)
except EOFError:
break
套路2:第一行是数量n
python
# 第一行:数据组数
# 后面n行:每行一个数据
n = int(input())
for _ in range(n):
data = input()
# 处理data
print(result)
套路3:一行多个数字
python
# 输入:10 20 30
# 读取并转换
nums = list(map(int, input().split()))
# 输出(空格分隔)
print(*nums)
# 或
print(' '.join(map(str, nums)))
套路4:格式化输出
python
# 要求:输出保留2位小数
score = 95.678
print(f"{score:.2f}") # 95.68
四、易错点总结 ⚠️
错误1:忘记类型转换
python
# ❌ 错误
age = input() # 这是字符串!
print(age + 1) # TypeError
# ✅ 正确
age = int(input())
print(age + 1)
错误2:输出格式不符
python
nums = [1, 2, 3]
# ❌ 题目要求:1 2 3
print(nums) # 输出:[1, 2, 3]
# ✅ 正确
print(*nums) # 输出:1 2 3
错误3:小数精度问题
python
num = 3.1415926
# ❌ 题目要求保留2位
print(num) # 3.1415926
# ✅ 正确
print(f"{num:.2f}") # 3.14
错误4:多组输入未处理EOF
python
# ❌ 只读一次
line = input()
# ✅ 循环读取
while True:
try:
line = input()
# 处理
except EOFError:
break
五、速查表(打印收藏)📌
格式化输出速查
python
保留2位小数: f"{x:.2f}" 或 "%.2f" % x
宽度10右对齐: f"{x:10}" 或 "%10d" % x
前导零补齐: f"{x:03d}" 或 "%03d" % x
十六进制: f"{x:x}" 或 "%x" % x
二进制: f"{x:b}" 或 bin(x)[2:]
类型转换速查
python
字符串→整数: int("123")
字符串→浮点: float("3.14")
浮点→整数: int(3.9) # 截断
四舍五入: round(3.5)
十六进制→十进制: int("FF", 16)
十进制→十六进制: hex(255)[2:]
字符→ASCII: ord('A')
ASCII→字符: chr(65)
🎯 现在测试掌握程度!
请不看资料回答:
问题1: 如何输出列表 [1, 2, 3] 为 1,2,3(逗号分隔,无空格)?
python
# 你的方法(最推荐)
print(*list, sep=',') # 1,2,3
# 方法2:join(也很常用)
print(','.join(map(str, list))) # 1,2,3
问题2: 如何将浮点数 3.1415926 保留3位小数输出?(3种方法)
python
num = 3.1415926
# 方法1:% 格式化
print("%.3f" % num) # 3.142
# 方法2:f-string(Python 3.6+)
print(f"{num:.3f}") # 3.142
# 方法3:format()
print("{:.3f}".format(num)) # 3.142
# 方法4:round()(不推荐用于输出,因为可能保留位数不够)
print(round(num, 3)) # 3.142
问题3: 如何将十进制 255 转为十六进制大写字符串 FF?
python
num = 255 # 注意:是整数,不是字符串
# 方法1:hex() + 切片 + upper()
print(hex(num)[2:].upper()) # FF
# 方法2:格式化输出(推荐)
print(f"{num:X}") # FF(大写X)
print(f"{num:x}") # ff(小写x)
# 方法3:format()
print("{:X}".format(num)) # FF
# 方法4:% 格式化
print("%X" % num) # FF
📚 Day 2:字符串操作专题
一、今日核心知识点(15分钟速学)
1. 字符串的基础操作
A. 索引与切片 ⭐⭐⭐
python
s = "Hello World"
# 索引(从0开始)
s[0] # 'H'
s[6] # 'W'
s[-1] # 'd'(倒数第一个)
s[-2] # 'l'(倒数第二个)
# 切片 [start:end:step]
s[0:5] # 'Hello'(包含0,不包含5)
s[:5] # 'Hello'(从头开始可省略0)
s[6:] # 'World'(到末尾可省略end)
s[:] # 'Hello World'(复制整个字符串)
# 步长
s[::2] # 'HloWrd'(每隔1个取一个)
s[::-1] # 'dlroW olleH'(反转字符串)⭐重要!
# 实用切片
s[-5:] # 'World'(最后5个字符)
s[:-6] # 'Hello'(除了最后6个字符)
切片规律总结:
python
s[start:end] # 从start到end-1
s[start:] # 从start到末尾
s[:end] # 从头到end-1
s[-n:] # 最后n个字符
s[:-n] # 除了最后n个字符
s[::-1] # 反转字符串
B. 字符串常用方法 ⭐⭐⭐
python
s = " Hello World "
# 1. 去除空白
s.strip() # 'Hello World'(去除两端空白)
s.lstrip() # 'Hello World '(去除左边空白)
s.rstrip() # ' Hello World'(去除右边空白)
# 2. 大小写转换
s = "Hello"
s.upper() # 'HELLO'
s.lower() # 'hello'
s.capitalize() # 'Hello'(首字母大写)
s.title() # 'Hello World'(每个单词首字母大写)
# 3. 查找与判断
s = "Hello World"
s.find('o') # 4(第一次出现的位置,找不到返回-1)
s.index('o') # 4(第一次出现的位置,找不到会报错)
s.count('o') # 2(出现次数)
s.startswith('He') # True
s.endswith('ld') # True
# 4. 替换
s.replace('o', '0') # 'Hell0 W0rld'
s.replace('l', 'L', 1) # 'HeLlo World'(只替换1次)
# 5. 拆分与合并
s = "apple,banana,orange"
s.split(',') # ['apple', 'banana', 'orange']
words = ['Hello', 'World']
' '.join(words) # 'Hello World'
','.join(words) # 'Hello,World'
C. 字符串判断方法 ⭐⭐
python
s = "Hello123"
# 类型判断
s.isdigit() # False(是否全是数字)
s.isalpha() # False(是否全是字母)
s.isalnum() # True(是否全是字母或数字)
s.isspace() # False(是否全是空白字符)
s.isupper() # False(是否全是大写)
s.islower() # False(是否全是小写)
# 示例
"123".isdigit() # True
"abc".isalpha() # True
"abc123".isalnum() # True
" ".isspace() # True
D. 字符串格式化(复习昨天)⭐⭐⭐
python
name = "Alice"
age = 20
score = 95.5
# 方法1:f-string(最推荐)
print(f"{name} is {age} years old, score: {score:.1f}")
# Alice is 20 years old, score: 95.5
# 方法2:% 格式化
print("%s is %d years old" % (name, age))
# Alice is 20 years old
# 方法3:format()
print("{} is {} years old".format(name, age))
# Alice is 20 years old
# 对齐与填充
print(f"{name:>10}") # ' Alice'(右对齐,宽度10)
print(f"{name:<10}") # 'Alice '(左对齐)
print(f"{name:^10}") # ' Alice '(居中)
print(f"{name:*^10}") # '**Alice***'(用*填充)
2. 字符串的不可变性 ⭐
python
s = "Hello"
# ❌ 错误:字符串不可修改
s[0] = 'h' # TypeError
# ✅ 正确:创建新字符串
s = 'h' + s[1:] # 'hello'
s = s.replace('H', 'h') # 'hello'
3. 字符串拼接技巧 ⭐⭐
python
# 方法1:+ 号(简单但效率低)
s = "Hello" + " " + "World" # 'Hello World'
# 方法2:join(推荐,效率高)
words = ["Hello", "World", "!"]
s = " ".join(words) # 'Hello World !'
# 方法3:f-string
name = "Bob"
s = f"Hello, {name}!" # 'Hello, Bob!'
# 性能对比(循环拼接时)
# ❌ 慢
result = ""
for i in range(1000):
result += str(i)
# ✅ 快
result = "".join(str(i) for i in range(1000))
二、牛客字符串题库(40分钟实战)
🔗 今日必做题目:https://www.nowcoder.com/exam/oj?page=1\&tab=Python篇\&topicId=288
今日任务清单(6道题):
-
✅ NP1 - 牛牛最好的朋友们
-
✅ NP2 - 单词的长度
-
✅ NP3 - 格式化输出(二)
-
✅ NP4 - 格式化输出(三)
-
✅ NP5 - 不用循环语句的重复输出
-
✅ NP6 - 截取用户名前10位
三、现在开始知识测试!
请回答以下问题(不要查资料,凭记忆回答):
问题1:字符串切片
给定字符串 s = "Python3.11"
请写出以下切片的结果:
-
s[0:6]= "Python" -
s[-4:]= "3.11" -
s[::-1]= "11.3nohtyP" -
s[::2]= "Pto31"
问题2:字符串方法
给定字符串 s = " Hello World "
如何实现以下操作(写出代码):
-
去除两端空格s.strip()
-
将所有字母转为小写s.lower()
-
将字符串反转s = s[::-1]
-
统计字母 'l' 出现的次数s.count('l')
问题3:字符串拆分与合并重点:****
给定字符串 s = "apple,banana,orange"
-
如何将它按逗号分割成列表?s.map(',')
-
如果想把列表
['a', 'b', 'c']用-连接成字符串'a-b-c',应该怎么写?s.join('-')
sql
# 问题1:分割
s = "apple,banana,orange"
result = s.split(',')
# ['apple', 'banana', 'orange']
# 问题2:合并
lst = ['a', 'b', 'c']
result = '-'.join(lst)
# 'a-b-c'
问题4:字符串格式化
给定 name = "Bob", age = 25
用 f-string 实现下输出:
-
Bob is 25 years oldprint(f"{name} is {age} years old") -
Name: Bob Age: 25(Name后面有5个空格) print(f"Name: {name} Age: {age}")
📚 Day 3:列表操作(上)
一、今日核心知识点(15分钟速学)
1. 列表的基础概念
A. 列表的特点 ⭐⭐
python
# 列表是可变的、有序的、可以包含不同类型元素的序列
# 创建列表
empty_list = []
nums = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True, [1, 2]] # 可以混合类型
nested = [[1, 2], [3, 4], [5, 6]] # 嵌套列表
# 列表推导式(快速创建)
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
B. 列表的索引与切片 ⭐⭐⭐
python
nums = [10, 20, 30, 40, 50]
# 索引访问
nums[0] # 10(第一个元素)
nums[-1] # 50(最后一个元素)
nums[-2] # 40(倒数第二个)
# 切片(和字符串一样)
nums[1:4] # [20, 30, 40](不包含索引4)
nums[:3] # [10, 20, 30]
nums[2:] # [30, 40, 50]
nums[:] # [10, 20, 30, 40, 50](复制列表)
nums[::-1] # [50, 40, 30, 20, 10](反转)⭐
nums[::2] # [10, 30, 50](每隔1个取1个)
# 切片赋值(修改多个元素)
nums[1:3] = [200, 300] # [10, 200, 300, 40, 50]
2. 列表的增加操作 ⭐⭐⭐
python
nums = [1, 2, 3]
# 方法1:append() - 在末尾添加单个元素
nums.append(4)
print(nums) # [1, 2, 3, 4]
nums.append([5, 6])
print(nums) # [1, 2, 3, 4, [5, 6]](整个列表作为一个元素)
# 方法2:extend() - 在末尾添加多个元素
nums = [1, 2, 3]
nums.extend([4, 5])
print(nums) # [1, 2, 3, 4, 5](拆开添加)
nums.extend("ab")
print(nums) # [1, 2, 3, 4, 5, 'a', 'b'](字符串被拆开)
# 方法3:insert() - 在指定位置插入元素
nums = [1, 2, 3]
nums.insert(1, 100) # 在索引1处插入100
print(nums) # [1, 100, 2, 3]
# 方法4:+ 运算符 - 连接列表(不修改原列表)
nums = [1, 2, 3]
result = nums + [4, 5]
print(result) # [1, 2, 3, 4, 5]
print(nums) # [1, 2, 3](原列表不变)
# 方法5:* 运算符 - 重复列表
nums = [1, 2]
result = nums * 3
print(result) # [1, 2, 1, 2, 1, 2]
append vs extend 对比(重要!)⭐⭐⭐
python
# append:把整个对象作为一个元素添加
nums = [1, 2, 3]
nums.append([4, 5])
print(nums) # [1, 2, 3, [4, 5]](长度变成4)
# extend:把对象中的每个元素依次添加
nums = [1, 2, 3]
nums.extend([4, 5])
print(nums) # [1, 2, 3, 4, 5](长度变成5)
# 记忆技巧:
# append = 追加一个(Append one item)
# extend = 扩展多个(Extend with multiple items)
3. 列表的删除操作 ⭐⭐⭐
python
nums = [10, 20, 30, 40, 50]
# 方法1:remove() - 删除第一个匹配的值
nums.remove(30)
print(nums) # [10, 20, 40, 50]
# 如果值不存在会报错
# nums.remove(100) # ValueError
# 方法2:pop() - 删除并返回指定索引的元素(默认最后一个)
nums = [10, 20, 30, 40, 50]
x = nums.pop() # 删除最后一个
print(x) # 50
print(nums) # [10, 20, 30, 40]
y = nums.pop(1) # 删除索引1
print(y) # 20
print(nums) # [10, 30, 40]
# 方法3:del - 删除指定索引或切片
nums = [10, 20, 30, 40, 50]
del nums[1] # 删除索引1
print(nums) # [10, 30, 40, 50]
del nums[1:3] # 删除切片
print(nums) # [10, 50]
# 方法4:clear() - 清空列表
nums.clear()
print(nums) # []
删除方法对比表 ⭐⭐⭐
4. 列表的修改与查询 ⭐⭐
python
nums = [10, 20, 30, 20, 50]
# 修改单个元素
nums[0] = 100
print(nums) # [100, 20, 30, 20, 50]
# 修改切片
nums[1:3] = [200, 300]
print(nums) # [100, 200, 300, 20, 50]
# 查询元素
nums.index(20) # 1(第一次出现的索引)
# nums.index(999) # ValueError(不存在会报错)
nums.count(20) # 2(出现次数)
# 判断元素是否存在
20 in nums # True
999 in nums # False
# 列表长度
len(nums) # 5
5. 列表的排序与反转 ⭐⭐⭐
python
nums = [30, 10, 50, 20, 40]
# 方法1:sort() - 原地排序(修改原列表)
nums.sort()
print(nums) # [10, 20, 30, 40, 50]
nums.sort(reverse=True) # 降序
print(nums) # [50, 40, 30, 20, 10]
# 方法2:sorted() - 返回新列表(不修改原列表)
nums = [30, 10, 50, 20, 40]
result = sorted(nums)
print(result) # [10, 20, 30, 40, 50]
print(nums) # [30, 10, 50, 20, 40](原列表不变)
# 方法3:reverse() - 原地反转(不排序)
nums = [1, 3, 2, 5, 4]
nums.reverse()
print(nums) # [4, 5, 2, 3, 1](只是反转,不排序)
# 方法4:切片反转(不修改原列表)
nums = [1, 2, 3, 4, 5]
result = nums[::-1]
print(result) # [5, 4, 3, 2, 1]
print(nums) # [1, 2, 3, 4, 5](原列表不变)
sort vs sorted 对比 ⭐⭐⭐
python
nums = [3, 1, 2]
# sort() - 修改原列表,无返回值
nums.sort()
print(nums) # [1, 2, 3]
# sorted() - 不修改原列表,返回新列表
nums = [3, 1, 2]
result = sorted(nums)
print(nums) # [3, 1, 2](原列表不变)
print(result) # [1, 2, 3]
# 记忆技巧:
# sort() - 就地排序(Sort in place)
# sorted() - 返回排序后的新列表(Sorted copy)
6. 列表的复制 ⭐⭐
python
# 浅拷贝(重要!)
nums = [1, 2, 3]
# 错误方式:赋值只是引用
a = nums
a.append(4)
print(nums) # [1, 2, 3, 4](原列表也变了!)
# 正确方式1:切片
nums = [1, 2, 3]
b = nums[:]
b.append(4)
print(nums) # [1, 2, 3](原列表不变)
print(b) # [1, 2, 3, 4]
# 正确方式2:copy()
c = nums.copy()
c.append(5)
print(nums) # [1, 2, 3]
print(c) # [1, 2, 3, 5]
# 正确方式3:list()
d = list(nums)
7. 列表推导式(进阶)⭐⭐⭐
python
# 基础列表推导式
squares = [x**2 for x in range(5)]
# [0, 1, 4, 9, 16]
# 带条件的列表推导式
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]
# 带 if-else 的列表推导式
result = [x if x > 0 else 0 for x in [-1, 2, -3, 4]]
# [0, 2, 0, 4]
# 嵌套列表推导式
matrix = [[i+j for j in range(3)] for i in range(3)]
# [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
# 多重循环
pairs = [(x, y) for x in [1, 2] for y in ['a', 'b']]
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
二、牛客列表题库(40分钟实战)
🔗 今日必做题目:https://www.nowcoder.com/exam/oj?page=1\&tab=Python篇\&topicId=288
今日任务清单(8道题):
-
✅ NP1 - 发送offer
-
✅ NP2 - 生成列表
-
✅ NP3 - 生成数字列表
-
✅ NP4 - 列表的长度
-
✅ NP5 - 增加派对名单(一)
-
✅ NP6 - 增加派对名单(二)
-
✅ NP7 - 删除简历
-
✅ NP8 - 删除好友
三、现在开始知识测试!
请回答以下问题(不要查资料,凭记忆回答):
问题1:append vs extend
给定列表 nums = [1, 2, 3]
请写出以下操作后的结果:
python
# 操作A
nums.append([4, 5])
# nums = [1, 2, 3, [4, 5]]
# 操作B(重新开始)
nums = [1, 2, 3]
nums.extend([4, 5])
# nums = [1, 2, 3, 4, 5]
问题2:删除操作
给定列表 nums = [10, 20, 30, 40, 50]
请写出代码实现以下需求:
- 删除值为 30 的元素(用 remove)
nums.remove(30)
- 删除索引为 1 的元素,并获取被删除的值(用 pop)
val = nums.pop(1)
- 删除索引 1 到 3(不包括3)的元素(用 del)
del nums[1:3]
问题3:排序与反转
给定列表 nums = [3, 1, 4, 1, 5]
回答以下问题:
nums.sort()和sorted(nums)有什么区别?
第一个会修改原列表,第二个不会修改原列表
nums.reverse()和nums[::-1]有什么区别?
nums会对原列表进行反转,后者不会对于原列表进行反转,会返回一个新的列表
问题4:列表推导式
请用列表推导式实现:
-
生成 0 到 9 的平方数列表 [x ** 2 for x in range(9)]
-
从列表
[1, -2, 3, -4, 5]中筛选出所有正数
python
# ✅ 更优雅的写法(直接遍历列表,不用索引)
[x for x in nums if x > 0]
# [1, 3, 5]
# 对比:
# 你的方式:通过索引访问 nums[i]
# 推荐方式:直接遍历元素 x
📊 Day 3 上半场成果总结
-
✅ 列表的创建与访问:索引、切片、遍历
-
✅ 列表的增加:append, extend, insert
-
✅ 列表的删除:remove, pop, del
-
✅ 列表的基础操作:长度、查找、判断
四、列表高级操作(15分钟速学)
8. 列表排序详解 ⭐⭐⭐
python
nums = [30, 10, 50, 20, 40]
# 基础排序
nums.sort() # [10, 20, 30, 40, 50](升序)
nums.sort(reverse=True) # [50, 40, 30, 20, 10](降序)
# 自定义排序 - key 参数
words = ["apple", "pie", "zoo", "a"]
# 按长度排序
words.sort(key=len)
# ['a', 'pie', 'zoo', 'apple']
# 按字母顺序排序
words.sort()
# ['a', 'apple', 'pie', 'zoo']
# 按最后一个字母排序
words.sort(key=lambda x: x[-1])
# ['a', 'apple', 'pie', 'zoo'](a, e, e, o)
# 复杂对象排序
students = [
("Alice", 85),
("Bob", 92),
("Charlie", 78)
]
# 按分数排序
students.sort(key=lambda x: x[1])
# [('Charlie', 78), ('Alice', 85), ('Bob', 92)]
# 按分数降序
students.sort(key=lambda x: x[1], reverse=True)
# [('Bob', 92), ('Alice', 85), ('Charlie', 78)]
# 按姓名排序
students.sort(key=lambda x: x[0])
# [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
2. 列表的统计与查找 ⭐⭐
python
nums = [1, 2, 3, 2, 4, 2, 5]
# 最大值、最小值、求和
max(nums) # 5
min(nums) # 1
sum(nums) # 19
# 计数
nums.count(2) # 3(2出现了3次)
# 查找索引
nums.index(3) # 2(第一次出现的位置)
# nums.index(10) # ValueError(不存在会报错)
# 判断存在
2 in nums # True
10 in nums # False
10 not in nums # True
# 所有、任意
all([True, True, True]) # True(所有都是True)
all([True, False, True]) # False(有False)
any([False, False, True]) # True(至少一个True)
any([False, False]) # False(全是False)
# 实用示例
nums = [2, 4, 6, 8]
all(x % 2 == 0 for x in nums) # True(所有都是偶数)
any(x > 5 for x in nums) # True(至少一个大于5)
3. 列表实现栈和队列 ⭐⭐⭐
栈(Stack)- 后进先出(LIFO)
python
# 用列表实现栈
stack = []
# 入栈(push)
stack.append(1)
stack.append(2)
stack.append(3)
# stack = [1, 2, 3]
# 出栈(pop)
x = stack.pop() # x = 3, stack = [1, 2]
y = stack.pop() # y = 2, stack = [1]
# 查看栈顶元素(不删除)
top = stack[-1] if stack else None
# 判断栈是否为空
is_empty = len(stack) == 0
队列(Queue)- 先进先出(FIFO)
python
# 用列表实现队列
queue = []
# 入队(enqueue)
queue.append(1)
queue.append(2)
queue.append(3)
# queue = [1, 2, 3]
# 出队(dequeue)
x = queue.pop(0) # x = 1, queue = [2, 3]
y = queue.pop(0) # y = 2, queue = [3]
# 查看队首元素(不删除)
front = queue[0] if queue else None
# 判断队列是否为空
is_empty = len(queue) == 0
# 注意:pop(0) 效率低,实际应用建议用 collections.deque
from collections import deque
queue = deque([1, 2, 3])
queue.append(4) # 入队
x = queue.popleft() # 出队(效率更高)
4. 列表的二维操作 ⭐⭐
python
# 创建二维列表
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 访问元素
matrix[0][0] # 1
matrix[1][2] # 6
matrix[2][1] # 8
# 遍历二维列表
for row in matrix:
for num in row:
print(num, end=' ')
# 输出:1 2 3 4 5 6 7 8 9
# 用推导式创建二维列表
# ❌ 错误方式(浅拷贝问题)
matrix = [[0] * 3] * 3
matrix[0][0] = 1
# [[1, 0, 0], [1, 0, 0], [1, 0, 0]](所有行都变了!)
# ✅ 正确方式
matrix = [[0] * 3 for _ in range(3)]
matrix[0][0] = 1
# [[1, 0, 0], [0, 0, 0], [0, 0, 0]](只改第一行)
# 矩阵转置
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = [[row[i] for row in matrix] for i in range(3)]
# [[1, 4], [2, 5], [3, 6]]
# 或者用 zip(更优雅)
transposed = list(zip(*matrix))
# [(1, 4), (2, 5), (3, 6)]
转置
5. 列表去重 ⭐⭐
python
nums = [1, 2, 2, 3, 3, 3, 4, 5, 5]
# 方法1:转集合(不保持顺序)
unique = list(set(nums))
# [1, 2, 3, 4, 5](顺序可能变化)
# 方法2:保持顺序
unique = []
for x in nums:
if x not in unique:
unique.append(x)
# [1, 2, 3, 4, 5]
# 方法3:用 dict.fromkeys(Python 3.7+ 保持顺序)
unique = list(dict.fromkeys(nums))
# [1, 2, 3, 4, 5]
# 方法4:推导式保持顺序
seen = set()
unique = [x for x in nums if not (x in seen or seen.add(x))]
# [1, 2, 3, 4, 5]
五、牛客列表题库(下半场)
🔗 继续完成剩余题目:
今日剩余任务(8道题):
-
✅ NP9 - 淘汰排名最后的学生
-
✅ NP10 - 有序的列表
-
✅ NP11 - 牛牛的反转列表
-
✅ NP12 - 朋友们的喜好
-
✅ NP13 - 密码游戏
-
✅ NP14 - 用列表实现栈
-
✅ NP15 - 用列表实现队列
-
✅ NP16 - 团队分组
六、现在开始知识测试!
请回答以下问题(不要查资料,凭记忆回答):
问题1:排序的 key 参数
给定列表:
python
words = ["apple", "zoo", "pie", "a"]
请写出代码:
- 按字符串长度排序(从短到长)
words.sort(key=len)
- 按字符串的最后一个字母排序
words.sort(key=lambda x: x[-1])
问题2:栈和队列
用列表实现栈和队列的操作:
- 栈操作:如何添加元素?如何删除元素?
使用append添加元素,使用pop删除元素
- 队列操作:如何添加元素?如何删除元素?
使用append添加元素,使用pop(0)删除元素
问题3:列表反转
给定 nums = [1, 2, 3, 4, 5]
- 如何反转列表(修改原列表)?
使用nums.reverse()
- 如何反转列表(返回新列表)?
使用nums[::-1]
- 写出两种方法
问题4:列表去重
给定 nums = [1, 2, 2, 3, 3, 4]
如何去除重复元素?(至少写出2种方法)
使用set来进行转化
使用dic.fromkeys进行转化