开发者社区> 问答> 正文

如何从起始两个单词相同的单词列表中获取单词列表

假设我的输入列表是:

["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

展开
收起
kun坤 2019-12-25 09:45:34 480 0
1 条回答
写回答
取消 提交回答
  • 这是使用的一种方法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']]
    
    2019-12-26 14:30:13
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载