假设我的输入列表是:
["customer service skill","sales representative",
"customer service","customer service experience"]
输出应该是:
[["sales representative"],["customer service skill","customer service","customer service experience"]]
有没有什么有效的方法来得到这个? 问题来源StackOverflow 地址:/questions/59466624/how-to-get-list-of-words-from-list-of-words-whose-starting-2-words-are-same
这是使用的一种方法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']]
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。