简体   繁体   English

数组中的 lambda 找不到变量值

[英]lambda in an array does not find variable values

i started in python a little while ago i need your help again, i have a csv file with cached data, and i use a for to go through the data filters and save the filtered data in an array as the example我不久前开始使用 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)

output:输出:

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

doesn't find the rest of the results, just the first one in the array, if you do a separate search it finds all the results没有找到其余的结果,只是数组中的第一个,如果您进行单独搜索,它会找到所有结果

i believe my lambda is incorrect so the wrong result我相信我的 lambda 不正确所以错误的结果

@stovfl already provided the answer for you issue: you can't read multiple times from a file object , @stovfl 已经为您提供了问题的答案:您无法从文件对象中多次读取,

to fix this you can store your file lines in a variable:要解决此问题,您可以将文件行存储在变量中:

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

First the if_find declaration is not a lambda function but rather a list comprehension try the code below if it suits your needs.首先, 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)

Output:输出:

['LMS']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM