我有以下串列:
sectors = ["A", "B"]
rows = [['1', '2', '3'], ['1', '2', '3', '4']]
seats = [['ab', 'abcd', 'ab'], ['ab', 'abcd', 'ab', 'abcd']]
我想創造像 A1a, A1b, A2a, A2b, A2c ...
這段代碼
combinations = []
for i in range(len(rows)):
c = list(zip_longest(repeat(sectors[i], len(rows[i])), rows[i], seats[i]))
combinations = c
for c in combinations:
for x in product(*c):
print("".join(x))
將所需結果列印為 A1a A1b A2a A2b A2c A2d A3a ...
能否以更好,更易讀的方式解決這個問題,我正在練習itertools,這對我來說有點困惑。
uj5u.com熱心網友回復:
不確定這是您想要的還是更優雅:
from itertools import chain, product
combinations = product(
sectors,
chain.from_iterable(chain.from_iterable(rows)),
chain.from_iterable(chain.from_iterable(seats)),
)
joined_combinations = map(lambda t: "".join(t), combinations)
list(joined_combinations)
# returns
['A1a', 'A1b', 'A1a', 'A1b', 'A1c', 'A1d', 'A1a', ...]
說明:應用兩次,chain.from_iterable您可以從嵌套串列中“解包”單個字符,然后創建未嵌套串列的專案的乘積(創建 3 元組),最后將每個 3 元組的專案連接在一起。
如果你想避免重復,你可以set()在product.
uj5u.com熱心網友回復:
由于您是從 3 個嵌套串列創建三元組,而不是笛卡爾積,我認為相應的子串列可能更直觀zip并使用回圈。
out = [sector row s for sector, rws, sts in zip(sectors, rows, seats)
for row, seat in zip(rws, sts) for s in seat]
如果我們想使用itertools.product,首先重復元素sectors以匹配其他串列的子串列的長度,而不是像上面最里面的??回圈那樣手動創建產品元素,我們迭代產品本身。當然,這很像您自己的方法。
repsectors = [repeat(sector, len(rows[i])) for i, sector in enumerate(sectors)]
out = [''.join(x) for tpl1 in zip(repsectors, rows, seats)
for tpl2 in zip(*tpl1) for x in itertools.product(*tpl2)]
輸出:
['A1a', 'A1b', 'A2a', 'A2b', 'A2c', 'A2d', 'A3a', 'A3b', 'B1a', 'B1b', 'B2a', 'B2b', 'B2c', 'B2d', 'B3a', 'B3b', 'B4a', 'B4b', 'B4c', 'B4d']
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/419228.html
標籤:
上一篇:在python中合并兩個元組串列
