将php循环转换为python

时间:2015-02-20 00:21:47

标签: php python arrays mongodb

我需要帮助将一些PHP代码转换为python。代码从mongodb游标获取结果,使用循环生成特定数组。我需要使用python代码生成相同的数组。

以下是mongodb结果的样子:

Array
(
    [0] => Array
        (
            [value] => example.com
            [host] => 246.156.18.221
        )

    [1] => Array
        (
            [value] => example2.com
            [host] => 246.156.18.221
        )
    [2] => Array
        (
            [value] => example3.com
            [host] => 96.235.15.251
        )

    [3] => Array
        (
            [value] => example4.com
            [host] => 96.235.15.251
        )
) 

以下是我在php循环中运行时的样子:

Array
(
    [246.156.18.221] => Array
        (
            [0] => Array
                (
            [value] => example.com
            [host] => 246.156.18.221
                )

            [1] => Array
                (
            [value] => example2.com
            [host] => 246.156.18.221
                )
    )
    [96.235.15.251] => Array
        (
            [0] => Array
                (
            [value] => example3.com
            [host] => 96.235.15.251
                )

            [1] => Array
                (
            [value] => example4.com
            [host] => 96.235.15.251
                )
    )
)

这是我用来生成第二个数组的php代码:

$result = array();
foreach($mongo_data as $data){
    $result[$data['host']][] = $data;
}
print_r($result);

现在,我需要使用python代码生成与第二个相同的数组。 有什么帮助吗?

2 个答案:

答案 0 :(得分:4)

from collections import defaultdict

def repack(mongo_data):
    result = defaultdict(list)
    for data in mongo_data:
        result[data["host"]].append(data)
    return result

然后

mongo_data = [
    {"value": "example.com",  "host": "246.156.18.221"},
    {"value": "example2.com", "host": "246.156.18.221"},
    {"value": "example3.com", "host": "96.235.15.251"},
    {"value": "example4.com", "host": "96.235.15.251"}
]

new_data = repack(mongo_data)

给出

{
    '246.156.18.221': [
        {'value': 'example.com', 'host': '246.156.18.221'},
        {'value': 'example2.com', 'host': '246.156.18.221'}
    ],
    '96.235.15.251': [
        {'value': 'example3.com', 'host': '96.235.15.251'},
        {'value': 'example4.com', 'host': '96.235.15.251'}
    ]
}

答案 1 :(得分:2)

print {data["host"]:data for data in mongo_data}

可能?