如何使用列表理解从.txt文件中筛选出列表?

2024-05-12 16:33:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在上Python课,我想不出一个带回家的小测验。我正在使用IDLE来编写代码

我们必须将名为names.txt的文件加载到列表中。该文件包含以下内容:

Joe Smith
000000
Jeff Mitchell
xxxxxxx
Benjamin Grant
12346

我需要过滤掉包含“xxxxxxx”或数字的行。我正在尝试将列表理解与以下代码一起使用:

> names = open(r'C:\Users\eesqu\Documents\Python\names1.txt','r')
> names_contents = names.read()
> filtered_names = [n for n in names_contents if n !='xxxxxxx']
> names.close()
> print(filtered_names)

但是,当我打印过滤后的_名称输出时,名称不会被过滤,而不是以下拉格式显示,它们的显示方式如下:

['J','o','e','S','m','i','t','h','n','0','0','0','0','n','J','e','f','f','m','i','t','c','h','e','l','l','n','x','x','x','x','x','n','n','J','a','i','n','G','r','n','t','n','n','n','n','1','2','3','4','6','n'\n']

我做错了什么?是否可以过滤掉“xxxxxxx”和数字

在我开始编写代码时,感谢您的支持


Tags: 文件代码txt名称列表namescontents数字
3条回答

names_contents是一个字符串,因此您要在这一行代码n !='xxxxxxx'中将字符串与字符进行比较。因此,首先必须将字符串拆分为代表每行的字符串列表。试试这个

lines = names_contents.split("\n")
filtered_names = [n for n in lines if n !='xxxxxxx']

你就快到了

names = open(r'C:\Users\eesqu\Documents\Python\names1.txt','r')
name_contents = names.readlines()  # list of lines
filtered_names = [n for n in name_contents if (not n.isnumeric() or n != 'xxxxxxx']

在这里发布之前,您可能想使用您最喜欢的搜索引擎查找内容。这是一个非常琐碎的问题

您可以使用readlines读取数据,并使用列表理解来过滤xxx

ss = '''
Joe Smith
000000
Jeff Mitchell
xxxxxxx
Benjamin Grant
12346
'''.strip()

with open('names.txt','w') as f: f.write(ss)  # write data file

###############################


with open('names.txt') as f:
   lns = f.readlines()
   xx = [ln.strip() for ln in lns if ln.strip() != 'xxxxxxx']
   
print('\n'.join(xx))

输出

Joe Smith
000000
Jeff Mitchell
Benjamin Grant
12346

相关问题 更多 >