2 回答

TA貢獻1873條經(jīng)驗 獲得超9個贊
僅對拆分后具有 2 個以上字母的元素使用itertools 組合。
import itertools
myList = ['A' , 'B' , 'C, D' , 'E, F, G', 'H' , 'I']
result = []
for item in myList:
item_split = item.split(',') #split each item on , separator
if len(item_split) <= 2:
result.append(item)
else: #more than 2 items after splitting. use combinations
result.extend(",".join(pair) for pair in itertools.combinations(item_split, 2))
print(result)
#Output:
['A', 'B', 'C, D', 'E, F', 'E, G', ' F, G', 'H', 'I']

TA貢獻2011條經(jīng)驗 獲得超2個贊
類似于Paritosh Singh 的回答,但有更多括號 :)
from operator import methodcaller
from itertools import chain, combinations
sep = ', '
splitter = methodcaller('split', sep)
def pairs(x):
return combinations(x, 2 if len(x) > 1 else 1)
joiner = sep.join
result = list(map(joiner,
chain.from_iterable(map(pairs,
map(splitter,
my_list)))))
[題外話提醒]
...如果你使用Coconut,可以說讀起來會更好一些:
from itertools import chain, combinations
my_list = ['A' , 'B' , 'C, D' , 'E, F, G', 'H' , 'I']
my_result = (my_list
|> split_each
|> pairs
|> chain.from_iterable
|> join_each
|> list
)
where:
split_each = map$(.split(", "))
pairs = map$((x) -> combinations(x, 2 if len(x) > 1 else 1))
join_each = map$(", ".join)
添加回答
舉報