数组中的lambda找不到变量值



我不久前开始使用python,我再次需要您的帮助,我有一个包含缓存数据的csv文件,我使用for来检查数据过滤器,并将过滤后的数据保存在数组中作为示例

filters = ['LMS', 'atx', 'arx-dsd']
search_result = []
cached_file = open("teste.csv", "r")
search_result.append(cached_file.readline())
for words in filters:
print(words)
if_find = [x for x in cached_file if words in x]
print(if_find)
if if_find:
search_result.extend(if_find)

输出:

LMS
[us-east-1a,windows,running,x86_64,IBM,LMS]
ATX
[]
arx-dsd
[]

没有找到其余的结果,只有数组中的第一个,如果你进行单独搜索,它会找到所有的结果

我认为我的lambda不正确,所以结果错误

@stovfl已经为您提供了问题的答案:您不能从文件对象中多次读取

要解决此问题,您可以将文件行存储在一个变量中:

with open("teste.csv", "r") as f:
cached_file = f.readlines()

首先,if_find声明不是lambda函数,而是列表理解如果符合您的需要,请尝试下面的代码。

filters = ['LMS','atx','arx-dsd']
search_result =[]
# replace search_result.append(cached_file.readline()) with the following..
# open csv file and create a list of strings using split
with open('test.csv','r') as f:
data = f.readline().strip().split(',')
#loop through the data which is list of strings
for i in data:
print(i)
if i in filters:    #check if string match in filters
search_result.append(i)
print(search_result)

输出:

['LMS']

相关内容

最新更新