How to create a dict equivalent in Python from Perl hash?

后端 未结 1 1945
孤城傲影
孤城傲影 2021-01-22 01:53

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 (/         


        
相关标签:
1条回答
  • 2021-01-22 02:14

    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():
        ...
    
    0 讨论(0)
提交回复
热议问题