当前位置: 动力学知识库 > 问答 > 编程问答 >

Get joined string from list of lists of strings in 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?

网友答案:
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).

网友答案:
>>> from itertools import product
>>> result = list(product(*lists))
>>> result = [separator.join(map(str, r)) for r in result]
>>> 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']

As @jpm pointed out, you don't really need to cast list to the product generator. I had these to see the results in my console, but they are not really needed here.

网友答案:

You can do this with builtins:

>>> map(separator.join, reduce(lambda c,n: [a+[str(b)] for b in n for a in c], lists, [[]]))
['a-1-i', 'b-1-i', 'a-2-i', 'b-2-i', 'a-1-ii', 'b-1-ii', 'a-2-ii', 'b-2-ii']
网友答案:
["%s%c%s%c%s" % (a, separator, b, separator, c) for a in lists[0] for b in lists[1] for c in lists[2]]
分享给朋友:
您可能感兴趣的文章:
随机阅读: