Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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.

like image 441
Oli Avatar asked Dec 07 '25 14:12

Oli


2 Answers

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']
like image 177
user2390182 Avatar answered Dec 10 '25 05:12

user2390182


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']}
like image 42
hipoglucido Avatar answered Dec 10 '25 05:12

hipoglucido