首页 > 解决方案 > Python:如何删除列表中的数字

问题描述

Python学习者在这里。所以我有一个 wordlist.txt 文件,每行一个单词。我想过滤掉以特定字母开头和结尾的特定单词。但是在我的 wordlist.txt 中,单词是用它们的出现次数列出的。

例如:

food 312
freak 36
cucumber 1

这是我的代码

wordList = open("full.txt","r", encoding="utf-8")
word = wordList.read().splitlines()

for i in word:
    if i.startswith("h") and i.endswith("e"):
        print(i)

但是由于列表中的每个项目最后都有数字,我无法过滤正确的单词。我不知道如何省略这些数字。

标签: pythonpython-3.xstartswithends-with

解决方案


尝试使用空格作为分隔符来分割行,并使用第一个值[0],即你的情况下的单词

for i in word:
    if i.split(" ")[0].startswith("h") and i.split(" ")[0].endswith("e"):
        print(i.split(" ")[0])

或者你可以只执行一次拆分

for i in word:
    w = i.split(" ")[0]
    if w.startswith("h") and w.endswith("e"):
        print(w)

编辑:根据下面的评论,如果碰巧有两个空格或一个制表符作为字段分隔符,您可能希望不使用参数或 None 进行拆分。

w = i.split()[0]

推荐阅读