简体   繁体   中英

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

I am trying to merge multiple arrays in python to make a single array just like array_merge() function in PHP

example: in 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 )

I have arrays in 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"},
        }

How will I merge these 3 condition + language_filter + qualification_filter to make a single array conditionstoaggregate

which I need to merge and put in a single array conditionstoaggregate = "" also if any array is empty it shouldn't be added in the conditionstoaggregate = ""

then pass in a MongoDB aggregate as - match filter must be an expression in an object

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

The purpose of this question is I need to add all arrays in single dimensions and pass it as a parameter in the MongoDB aggregate function also if an array is empty it shouldn't be merged or passed? is there any way to do this?

after all your suggestion I tried but not help because your methods are for lists not object for reference see below I tried both method of list and itertools one by one.

  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",
        }
    },
]

it gives an error in MongoDB aggregation -

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'

so I need to pass as an object in aggregation pipeline by merging all array into one

You can also use the extend method over a list

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

[1, 2, 3, 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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