简体   繁体   中英

How to create lists from every item of an existing list in python 2.7.11?

I am trying to generate lists from the elements of a list in python. For example: there is a list with the following information: list=['AB4', 'AB3','AC3', 'BC4', 'BC5'] This is the exact format of the elements of the list. I suppouse to create list for every element, separate for the letters (considering both letters as one block) and separate for the numbers, that will contain the missing character from their string. Here is what I mean:

 AB:['4', '3']
 AC:['3']
 BC:['4', '5']
 4:['AB', 'BC']
 3:['AB', 'AC']
 5:['BC']

These are the lists that I should generate from the original list. There is no limitation to the elements of the original list, and their format is exactly like in the example "two letters and a number".

Thank you in advance.

You can use regexes (the re module) and a defaultdict to accomplish this. The following will work for arbitrary lengths of the non-digit/digit parts of your input strings:

import re
from collections import defaultdict

def str_dig(s):  # str_dig('ABC345') -> ('ABC', '345')
    return re.match('([^\d]+)(\d+)', s).groups()

lst=['AB4', 'AB3','AC3', 'BC4', 'BC5']  # do NOT shadow list!

d = defaultdict(list)
for x, y in map(str_dig, lst):  # map applies the str_dig function to all in lst
    d[x].append(y)
    d[y].append(x)

# d['AB']: ['4', '3'], d['3']: ['AB', 'AC']

This will do it:

from collections import defaultdict
l=['AB4', 'AB3','AC3', 'BC4', 'BC5']
result=defaultdict(list)
for item in l:  
    #If you want numbers to be numbers and not strings replace item[2:] with int(item[2:])  
    result[item[:2]].append(item[2:])
    result[item[2:]].append(item[:2])

And you can use this to print it just as you want:

import pprint
pp = pprint.PrettyPrinter()
pp.pprint(result)

output:

{'3': ['AB', 'AC'],
 '4': ['AB', 'BC'],
 '5': ['BC'],
 'AB': ['4', '3'],
 'AC': ['3'],
 'BC': ['4', '5']}

How about this,

import itertools
import operator

l = ['AB4', 'AB3','AC3', 'BC4', 'BC5']
lists = [(s[:2], s[2]) for s in l]      # [('AB', '4'), ('AB', '3'), ('AC', '3'), ('BC', '4'), ('BC', '5')]

results = dict()

for name, group in itertools.groupby(sorted(lists, key=operator.itemgetter(0)), key=operator.itemgetter(0)):
    results[name] = map(operator.itemgetter(1), group)

for name, group in itertools.groupby(sorted(lists, key=operator.itemgetter(1)), key=operator.itemgetter(1)):
    results[name] = map(operator.itemgetter(0), group)

print(results)
# Output
{   'AC': ['3'], 
    'AB': ['4', '3'], 
    'BC': ['4', '5'], 
    '3':  ['AB', 'AC'], 
    '5':  ['BC'], 
    '4':  ['AB', 'BC']}

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