[英]Merge sublist with each item of list
I have a list of lists and I need to join them together with each item of list.我有一个列表列表,我需要将它们与列表的每个项目一起加入。 See example below:请参见下面的示例:
my_list = [1, [2, 3], [4, 5]]
Expected result:预期结果:
['1', '1.2', '1.3', '1.2.4', '1.2.5', '1.3.4', '1.3.5']
I tried to write the logic but one or other items are always missing.我尝试编写逻辑,但总是缺少一项或多项。
def join_lists(result, prefix, items):
if not items:
result.append('.'.join(map(str, prefix)))
else:
for i, item in enumerate(items[0]):
join_lists(result, prefix + [item], items[1:])
join_lists(result, prefix, items[1:])
my_list = [1, [2, 3], [4, 5]]
result = []
join_lists(result, [1], my_list)
print(result)
will produce:将产生:
Output: ['1', '1.2', '1.3', '1.2.4', '1.2.5', '1.3.4', '1.3.5']
You could do this:你可以这样做:
import itertools
my_list = [1, [2, 3], [4, 5]]
# First convert each scalar into list
my_list = [[e] if not isinstance(e, list) else e for e in my_list]
# and then each element into str
my_list = [list(map(str, e)) for e in my_list]
# Then initialize a result list and keep extending with product of the result
# with the next element in my_list
t = my_list[0]
out = []
out.extend(t)
for lst in my_list[1:]:
t = list(map('.'.join, itertools.product(t, lst)))
out.extend(t)
print(out)
['1', '1.2', '1.3', '1.2.4', '1.2.5', '1.3.4', '1.3.5']
# for the input my_list = [[1,2],3,[4,5]]
my_list = [[1,2],3,[4,5]]
print(out)
['1', '2', '1.3', '2.3', '1.3.4', '1.3.5', '2.3.4', '2.3.5']
Using itertools.accumulate
:使用itertools.accumulate
:
from itertools import accumulate, product
# ensure sub-items are lists
def as_lst(x):
return x if isinstance(x, list) else [str(x)]
out = [str(e) for l in (accumulate(map(as_lst, my_list),
lambda *x: ['.'.join(map(str, y))
for y in product(*x)])
)
for e in as_lst(l)]
print(out)
Output: Output:
['1', '1.2', '1.3', '1.2.4', '1.2.5', '1.3.4', '1.3.5']
Output for my_list=[[1,2],3,[4,5]]
: Output 为my_list=[[1,2],3,[4,5]]
:
['1', '2', '1.3', '2.3', '1.3.4', '1.3.5', '2.3.4', '2.3.5']
result = []结果 = []
def join_lists(prefix, items): for item in items: if isinstance(item, list): join_lists(prefix + "." + str(item[0]), item[1:]) else: result.append(prefix + "." + str(item)) def join_lists(prefix, items): 对于 item in items: if isinstance(item, list): join_lists(prefix + "." + str(item[0]), item[1:]) else: result.append(prefix + "." + 海峡(项目))
join_lists("1", my_list[1:]) join_lists("1", my_list[1:])
print(result)打印(结果)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.