如何从开头两个单词相同的单词列表中获取单词列表

时间:2019-12-24 09:30:20

标签: python python-3.x list

假设我的输入列表是:

["customer service skill","sales representative",
 "customer service","customer service experience"]

输出应为:

[["sales representative"],["customer service skill","customer service","customer service experience"]]

有什么有效的方法可以得到这个吗?

1 个答案:

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