Oli Oli - 5 months ago 9
Python Question

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.

Answer

This will do it:

l=['AB4', 'AB3','AC3', 'BC4', 'BC5']
result=dict()
def addValue(key,value):
    try:
        result[key].append(value)
    except:
        result[key]=[value]
for item in l:
    addValue(item[:2],item[2:])
    addValue(item[2:],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']}
Comments