如何使用Perl哈希在Python中创建一个与dict等价的对等函数? [英] How to create a dict equivalent in Python from Perl hash?

查看:152
本文介绍了如何使用Perl哈希在Python中创建一个与dict等价的对等函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我的Perl代码:

  my%sites; 

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

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

如何在Python中执行相同操作?

解决方案

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

  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():
    ...

这篇关于如何使用Perl哈希在Python中创建一个与dict等价的对等函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆