【问题标题】:lambda in an array does not find variable values数组中的 lambda 找不到变量值
【发布时间】:2020-06-13 09:51:25
【问题描述】:

我不久前开始使用 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 不正确,所以结果错误

【问题讨论】:

  • “我的 lambda 不正确”:没有lambda ...,你不能从一个文件句柄中多次读取,向上读取在reading-and-writing-files
  • @Mateus Silva,这行是否正确:if_find = [x for x in cached_file if words in x]?
  • @AaymanKhalid 这条线是正确的,没有循环

标签: python arrays for-loop lambda


【解决方案1】:

@stovfl 已经为您的问题提供了答案:您无法从file object 中多次阅读,

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

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

【讨论】:

    【解决方案2】:

    首先,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']
    

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多