簡體   English   中英

將子列表與列表的每個項目合並

[英]Merge sublist with each item of list

我有一個列表列表,我需要將它們與列表的每個項目一起加入。 請參見下面的示例:

my_list = [1, [2, 3], [4, 5]]

預期結果:

['1', '1.2', '1.3', '1.2.4', '1.2.5', '1.3.4', '1.3.5']

我嘗試編寫邏輯,但總是缺少一項或多項。

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)

將產生:

Output: ['1', '1.2', '1.3', '1.2.4', '1.2.5', '1.3.4', '1.3.5']

你可以這樣做:

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']

使用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:

['1', '1.2', '1.3', '1.2.4', '1.2.5', '1.3.4', '1.3.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']

結果 = []

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:])

打印(結果)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM