Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get joined string from list of lists of strings in Python

Tags:

python

I have a list of lists and a separator string like this:

lists = [
    ['a', 'b'],
    [1, 2],
    ['i', 'ii'],
]
separator = '-'

As result I want to have a list of strings combined with separator string from the strings in the sub lists:

result = [
    'a-1-i', 
    'a-1-ii', 
    'a-2-i', 
    'a-2-ii',
    'b-1-i', 
    'b-1-ii', 
    'b-2-i', 
    'b-2-ii',
]

Order in result is irrelevant.

How can I do this?

like image 738
Martin Avatar asked Oct 09 '12 07:10

Martin


People also ask

How do you join a list of strings in one string in Python?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

How do you join two lists of strings in Python?

Using append() function One simple and popular way to merge(join) two lists in Python is using the in-built append() method of python. The append() method in python adds a single item to the existing list.

How do you find a string in a list in a list Python?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.


1 Answers

from itertools import product
result = [separator.join(map(str,x)) for x in product(*lists)]

itertools.product returns an iterator that produces the cartesian product of the provided iterables. We need to map str over the resultant tuples, since some of the values are ints. Finally, we can join the stringified tuples and throw the whole thing inside a list comprehension (or generator expression if dealing with a large dataset, and you just need it for iteration).

like image 182
jpm Avatar answered Sep 20 '22 16:09

jpm