簡體   English   中英

如何將多個 arrays 合並成一個數組 python?

[英]How to merge multiple arrays in to make a single array python?

我正在嘗試合並 python 中的多個 arrays 以創建一個數組,就像 PHP 中的array_merge() function

示例:在 PHP

$condition  = "";
$a1=array("red","green");
$a2=array("blue","yellow");
$condition = (array_merge($a1,$a2));
 //and output of $condition like -
Array ( [0] => red [1] => green [2] => blue [3] => yellow )

我有 arrays 在python -

qualification_filter = []
language_filter = []
conditionstoaggregate  = ""

if qualified == 1:
   qualification_filter = {"qualification": {"$gt": {"size": 0}}}

if len(language) > 0 and language[0] != "undefined":
   language_filter = {"language": {"$in": language}}


condition = {
  "rejected": {"$ne": "1"},
  "clientid": 22,
  "keyword.keytpe": {"$in": "finals"},
        }

我將如何合並這 3 個condition + language_filter + qualification_filter來制作一個數組conditionstoaggregate

我需要合並並放入單個數組conditionstoaggregate = ""如果任何數組為空,則不應將其添加到conditionstoaggregate = ""

然后傳入MongoDB 聚合作為- match filter must be an expression in an object

aggregate = [
    {"$match": conditionstoaggregate},
    {
        "$lookup": {
            "from": "companyissue",
            "localField": "keyword.keyid",
            "foreignField": "issueid",
            "as": "issue_company",
        }
    },
]

這個問題的目的是我需要在單個維度中添加所有 arrays 並將其作為參數傳遞到 MongoDB 聚合 function 中,如果數組為空,則不應合並或傳遞? 有什么辦法嗎?

在你提出所有建議后,我嘗試了但沒有幫助,因為你的方法是針對列表的,而不是 object 供參考,請參見下文,我一一嘗試了列表方法和 itertools 方法。

  conditionstoaggregate = itertools.chain([condition], [language_filter], [qualification_filter])
     conditionstoaggregate = [condition] + [language_filter] + [qualification_filter]

    aggregate = [
    {"$match": conditionstoaggregate},
    {
        "$lookup": {
            "from": "companyissue",
            "localField": "keyword.keyid",
            "foreignField": "issueid",
            "as": "issue_company",
        }
    },
]

它在 MongoDB 聚合中給出錯誤-

pymongo.errors.OperationFailure: the match filter must be an expression in an object, full error: {'operationTime': Timestamp(1670994472, 1), 'ok': 0.0, 'errmsg': 'the match filter must be an expression in an object'

所以我需要通過將所有數組合並為一個來在聚合管道中作為 object 傳遞

您還可以在列表上使用擴展方法

list1 = [1, 2]
list2 = [3, 4]
list1.extend(list2)
print(list1)

[1, 2, 3, 4]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM