Home > Enterprise >  Splitting str in list
Splitting str in list

Time:07-07

I'm trying to write a function that returns list of lists with all possible combination.

It's supposed to return this:

[['Moscow', 'Oslo', 'Boston', 'Berlin'],
 ['Moscow', 'Oslo', 'Sydney', 'Berlin'],
 ['Moscow', 'Paris', 'Boston', 'Berlin'],
 ['Moscow', 'Paris', 'Sydney', 'Berlin']]

and when I call the function

pathway('Moscow', [['Oslo', 'Paris'], ['Boston', 'Sydney']], 'Berlin')

I get this:

[['Moscow', 'Oslo, Boston', 'Berlin'],
 ['Moscow', 'Oslo, Sydney', 'Berlin'],
 ['Moscow', 'Paris, Boston', 'Berlin'],
 ['Moscow', 'Paris, Sydney', 'Berlin']]

Here is my function:

def pathway(city_from, city_array, city_to):
    paths = []
    cities = itertools.product(*city_array)
    cities = [', '.join(map(str, x)) for x in cities]
    for i in cities:
        i = str(i)
        path = city_from, i, city_to
        paths.append(list(path))
    return paths

How can it be fixed?

CodePudding user response:

This will do precisely what you specified:

def pathway(city_from, city_array, city_to):
    return [[city_from, *c, city_to] 
           for c in itertools.product(*city_array)]

CodePudding user response:

A string whose contents looks like a list is not the same as an actual list:

def pathway(city_from, city_array, city_to):
    paths = []
    cities = itertools.product(*city_array)
    for i in cities:
        path = [city_from]   list(i)   [city_to]
        paths.append(list(path))
    return paths
  • Related