☰
Python入门经典题目实战应用指南
2026/10/16 7:23:05 网站建设 项目流程

前言


入门阶段刷的那些"经典题"——反转字符串、判断回文、统计词频、字符串去重、单词计数——看着零散,其实考的是同一批基本功:索引与切片、循环与条件、字典与计数器、以及排序。把这些基本功用对,题目本身往往只有几行;用错,就会写出又长又慢的代码。


这里要澄清一个常见的做法误区:很多教程把"字符串去重""判断回文"写成手写双层循环,然后说这是"算法思维"。但 Python 的标准库为这类需求准备了更合适的工具——切片[::-1]、dict.fromkeys、collections.Counter、sorted。先用对工具,再谈优化,这是本文的基调。


本文挑选几道最有代表性的入门题,每题给出可直接运行的写法,并说明它考的知识点。代码基于 Python 3.8 及以上。Python 2.7 已于 2020 年 1 月 1 日停止维护,本文一律用 Python 3 的写法。


一、反转与回文


反转是一行的事:切片[::-1]用负步长从后往前取。


# 适用于 Python 3.8+
s = "hello"
print(s[::-1]) # olleh

def is_palindrome(s: str) -> bool:
return s == s[::-1]

print(is_palindrome("level")) # True
print(is_palindrome("Level")) # False 大小写不同

如果要"忽略大小写和空格"的回文判定,先归一化再比:


# 适用于 Python 3.8+
def is_loose_palindrome(s: str) -> bool:
normalized = [ch.lower() for ch in s if ch.isalnum()]
t = "".join(normalized)
return t == t[::-1]

print(is_loose_palindrome("A man, a plan, a canal: Panama")) # True

isalnum()过滤掉标点和空格,lower()抹平大小写。注意反转用[::-1],比手写循环清晰得多。


二、词频统计


统计每个字符或每个单词出现多少次,是入门高频题。collections.Counter就是为这件事准备的:


Counter(iterable=None, /, **kwds)

# 适用于 Python 3.8+
from collections import Counter

print(Counter("hello"))
# Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

words = "the cat the hat the".split()
c = Counter(words)
print(c.most_common(2)) # [('the', 3), ('cat', 1)]
print(c["dog"]) # 0 缺键返回 0,不抛异常

Counter有两个好用的点:取不存在的键返回0(普通字典会抛KeyError),以及most_common(n)直接给出出现最多的前 n 项。要按大小写无关统计,先统一成casefold():


# 适用于 Python 3.8+
from collections import Counter

text = "The the THE"
print(Counter(w.casefold() for w in text.split())) # Counter({'the': 3})

三、字符串去重且保持顺序


"去掉重复字符"如果还要求保留第一次出现的顺序,用dict.fromkeys最简洁。它按插入顺序建键,重复的键自然只保留一份:


# 适用于 Python 3.8+
s = "abracadabra"
print("".join(dict.fromkeys(s))) # abrcd

推演一下:dict.fromkeys("abracadabra")依次插入a、b、r、c、d,后面重复的a、b、a只更新值、不改变位置,所以键是a、b、r、c、d,拼回字符串就是abrcd。这个写法依赖"字典保持插入顺序"——这一点从 Python 3.7 起是语言保证(3.6 是实现细节,不应依赖)。


只想"去重不管顺序"也可以用set,但要清楚set不保证顺序,别指望结果稳定。


四、单词计数与字符分类


统计单词个数,split()不带参数就能处理连续空格:


# 适用于 Python 3.8+
sentence = " Python is fun "
print(sentence.split()) # ['Python', 'is', 'fun']
print(len(sentence.split())) # 3

分类统计各类字符的个数,字典加is*判断即可:


# 适用于 Python 3.8+
def classify(s: str) -> dict:
result = {"digit": 0, "alpha": 0, "space": 0, "other": 0}
for ch in s:
if ch.isdigit():
result["digit"] += 1
elif ch.isalpha():
result["alpha"] += 1
elif ch.isspace():
result["space"] += 1
else:
result["other"] += 1
return result

print(classify("abc 123!中"))
# {'digit': 3, 'alpha': 4, 'space': 1, 'other': 1}

"abc 123!中":字母是a、b、c和中(isalpha()对汉字返回True)共 4 个,数字 3 个,空格 1 个,!1 个。


五、排序:记住 sort 与 sorted 的区别


按词频排序、按字典序排序是常见收尾动作。




函数是否原地返回值



list.sort(...)原地排序返回None

sorted(iterable, key=..., reverse=...)生成新列表返回排好序的新列表



# 适用于 Python 3.8+
words = ["banana", "apple", "cherry"]
print(sorted(words)) # ['apple', 'banana', 'cherry']
print(sorted(words, key=len)) # ['apple', 'banana', 'cherry'] 按长度
print(sorted(words, reverse=True)) # ['cherry', 'banana', 'apple']

nums = [3, 1, 2]
result = nums.sort() # 注意:返回 None
print(result) # None
print(nums) # [1, 2, 3] 原列表被就地改了

sort返回None是入门阶段最容易踩的坑之一:写成nums = nums.sort()会把列表直接变成None。


实战:词频排行榜


把上面的点拼成一个完整的小程序:读一段文本,统计出现最多的单词,按次数从高到低输出。


# 适用于 Python 3.8+
from collections import Counter
import re

TEXT = """
Python is great. Python is simple.
Python is readable, and Python is fun!
"""

def top_words(text: str, n: int = 3):
# 用正则取出所有"字母或数字组成的词",统一小写
words = re.findall(r"[A-Za-z]+", text.casefold())
counter = Counter(words)
# most_common 已按次数降序;次数相同的再按字典序排,保证结果稳定
return sorted(counter.items(), key=lambda kv: (-kv[1], kv[0]))[:n]

for word, count in top_words(TEXT, 3):
print(f"{word}: {count}")

# is: 4
# python: 4
# and: 1

re.findall把标点排除干净,casefold()统一大小写,Counter计数,最后sorted用(-次数, 词)作为键:主序按次数降序(取负号实现降序),次序按词升序,这样即使次数相同,输出也稳定不跳动。


常见坑点



  1. 用手写循环反转字符串


❌out = ""; for ch in s: out = ch + out,又慢又长


✅s[::-1]一步到位



  1. sort()的返回值当结果


❌nums = [3, 1, 2]; nums = nums.sort(),nums变成None


✅nums.sort()就地排序不返回值;要新列表用nums = sorted(nums)



  1. 用set去重还指望顺序


❌"".join(set("abracadabra")),输出顺序不保证


✅ 要保序用"".join(dict.fromkeys(s))(依赖 3.7 起字典保序的语言保证)



  1. 普通字典取不存在的键


❌d = {}; d["x"] += 1→KeyError


✅ 计数用collections.Counter,或用d.get("x", 0) + 1



  1. split()和split(" ")混用


❌"a b".split(" ")得到['a', '', 'b'],多出空串


✅ 按空白分词用无参split(),连续空白会合并



  1. 忽略大小写导致词频被拆散


❌Counter("The the THE".split())得到三个不同的键


✅ 先casefold()(或lower())再统计



  1. 列表推导式里直接改原列表


❌for w in words: words.remove(w),边遍历边改,结果不可预期


✅ 用推导式生成新列表:[w for w in words if w]



  1. 沿用 Python 2 的写法


❌ 用print语句、dict.iteritems()、xrange、unicode


✅ Python 3 里print是函数、遍历字典用.items()、range本身惰性;Python 2.7 已于 2020 年 1 月 1 日 EOL


总结




经典题推荐工具关键点



反转字符串s[::-1]负步长切片

判回文s == s[::-1]需要时先casefold()归一化

词频统计collections.Counter缺键返回 0,most_common(n)

保序去重"".join(dict.fromkeys(s))3.7 起字典保序是语言保证

单词计数s.split()无参时连续空白算一个

字符分类字典 +is*方法isalpha()对汉字也为真

排序sorted(...)/list.sort()sort就地且返回None



入门题的价值不在于题目多难,而在于它逼你熟悉"切片、字典、计数器、排序"这几件常用工具。大多数经典题在 Python 里都有一行或几行的标准写法,先掌握这些写法,再去理解背后的复杂度;等到需要自己实现时,你已经知道"标准库是怎么做的"了。真正的坑往往不在算法,而在sort()返回None、set不保序、split(" ")留空串这些细节上。




需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询