且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Perl哈希在Python中创建一个与dict等价的对等函数?

更新时间:2023-11-30 14:08:10

这是一个非常直接的翻译:

  import re 

re_domain = re.compile(。* \。(。*))
sites = {}

索引中的索引:
match = re_domain.search(index)
如果匹配:
sites.setdefault(match.group(1),[])。append(index)

site.keys()中的site_key:
devices = sites [site_key]

更多Pythonic的方式就是这样做:

 导入集合
导入os.path

sites = collections.defaultdict(list)

用于索引索引:
root,ext = os.path.splitext(索引)
sites [ext] .append( index)

for site_key,sites.iteritems()中的设备:
...


I'm new to python, and can't get my head around dict hashes.

Here's my perl code:

my %sites;

foreach (@indexes) {
       push @{$sites{$1}}, $_ if (/.*\.(.*)/);
}

foreach my $sites (keys %sites)
{
        @devices = @{$sites{$sites}};
        #Do stuff

How do I do the same in Python?

This is a pretty direct translation:

import re

re_domain = re.compile(".*\.(.*)")
sites = {}

for index in indexes:
    match = re_domain.search(index)
    if match:
        sites.setdefault(match.group(1), []).append(index)

for site_key in sites.keys():
    devices = sites[site_key]

A more Pythonic way would be to do it like this:

import collections
import os.path

sites = collections.defaultdict(list)

for index in indexes:
    root, ext = os.path.splitext(index)
    sites[ext].append(index)

for site_key, devices in sites.iteritems():
    ...