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?
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With