假设我的输入列表是:
["customer service skill","sales representative",
"customer service","customer service experience"]
输出应为:
[["sales representative"],["customer service skill","customer service","customer service experience"]]
有什么有效的方法可以得到这个吗?
答案 0 :(得分:0)
这是使用collections.defaultdict
的一种方法。
例如:
from collections import defaultdict
lst = ["customer service skill","sales representative","customer service","customer service experience"]
result = defaultdict(list)
for i in lst:
result[tuple(i.split()[:2])].append(i) #Key = starting two words
print(list(result.values()))
或使用dict.setdefault
例如:
lst = ["customer service skill","sales representative","customer service","customer service experience"]
result = {}
for i in lst:
result.setdefault(tuple(i.split()[:2]), []).append(i) #Key = starting two words
print(list(result.values()))
输出:
[['customer service skill', 'customer service', 'customer service experience'], ['sales representative']]