You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:如何从列表中提取纯字母单词?

问题解决

你的问题出在列表的+=操作上:当你用cleared_list += word时,Python会把字符串word当成可迭代对象,逐个拆分字符添加到列表里,所以最终得到的是单个字母的集合,而不是完整的单词。

要添加整个单词到列表,应该用列表的append()方法,修改后的代码如下:

words = ['1', 'example', '2.3', 'hello', 'etc']

cleared_list = []
for word in words:
    if word.isalpha():
        cleared_list.append(word)  # 改用append方法添加完整单词

print(cleared_list)

运行这段代码,输出会是['example', 'hello', 'etc'],正好是你需要的纯字母单词列表。

另外,你也可以用更简洁的列表推导式实现相同功能:

words = ['1', 'example', '2.3', 'hello', 'etc']
cleared_list = [word for word in words if word.isalpha()]
print(cleared_list)

内容的提问来源于stack exchange,提问作者yesi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:36:15