如何使用lambda函数在列表/数组中查找字母匹配的字符串?

2024-04-19 15:41:50 发布

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

我正在使用lambda函数、python3.6和mongodbatlas。在mongodb中,我有一个这样的收藏。集合名称配置文件。下面是集合结构。你知道吗

"_id" : ObjectId("5db234df92b0ce00016932f3")
"username" : "testing"
"channel" : [ "abc", "efg", "cde", "xyz" ]
"about" : "this is a test case"

我们有多个类似于上面的行。现在我正在使用python,我编写lambda函数来查找通道中匹配字母的字符串数组.查找下面是lambda函数。你知道吗

profile = db.profile
name = event['cname']

ch = list(profile.aggregate([{
    "$match" : { "username" : "testing" }
    }, 
    {
        "$project" : {
            "channel" : 1
            }
    }
    ]))

ch1 = json.loads(json.dumps(ch, default=json_util.default))
ch2 = [document["channel"] for document in ch1]
new_list = []
for i in ch2:
    if(re.findall(name, i)):
        new_list.append(i)  
return new_list

我通过了“cname”:“c”。但是我犯了这样的错误。你知道吗

Response:
{
 "errorMessage": "expected string or bytes-like object",
 "errorType": "TypeError",
 "stackTrace": [
[
  "/var/task/lambda_function.py",
  51,
  "lambda_handler",
  "if(re.findall(search, i)):"
],
[
  "/var/lang/lib/python3.6/re.py",
  222,
  "findall",
  "return _compile(pattern, flags).findall(string)"
]
]
}

我试过了检索而且,我得到相同的,我需要如下输出。你知道吗

Input: "cname" : "c"
output: "abc"
        "cde"

你能帮我解决这个问题吗,提前谢谢。你知道吗


Tags: lambda函数namerejsonnewchannelusername
1条回答
网友
1楼 · 发布于 2024-04-19 15:41:50

遵循以下代码:

 ch2 = [document["channel"] for document in ch]
 new_list = []

 for word in ch2[0]:
    print(word)
    if(re.findall(name, word)):
        new_list.append(word)

  return new_list

这个问题已经解决了

相关问题 更多 >