简体   繁体   English

如何在包含相同首字母python的列表中查找单词

[英]How to find words in a list that contain the same first letter python

Write a function common_start(word_list) that takes in parameter a list of words.编写一个函数common_start(word_list) ,它接受一个单词列表作为参数。 This function must return a new list containing all words that start with the same letter as at least one other word in the list.此函数必须返回一个新列表,其中包含以与列表中至少一个其他单词相同的字母开头的所有单词。

input : ['file', 'edit', 'view', 'insert', 'format']输入:['文件','编辑','查看','插入','格式']
output : ['file', 'format']输出:['文件','格式']

A one line solution, if you want一个单行解决方案,如果你想

def common_start(input_list):
    return [word for word in input_list if sum([w.startswith(word[0]) for w in input_list]) > 1]

This should work for you.这应该对你有用。 In this case I'm ignoring the duplicated words.在这种情况下,我忽略了重复的单词。

def common_start(word_list):
    output = set()

    for word in word_list:
        for first_letter in word_list:
            if word == first_letter:
                next
            elif word[0] == first_letter[0]:
                output.add(word)
    return list(output)

Input: ['tara', 'file', 'edit', 'view', 'insert', 'format','test']输入:['tara', 'file', 'edit', 'view', 'insert', 'format','test']

Output: ['tara', 'file', 'format', 'test']输出:['tara', 'file', 'format', 'test']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 返回包含字母的单词列表 - Return a list of words that contain a letter 如何在单词列表中找到字母的位置 - How to find the position of a letter in a list of words Python:如何在句子的单词列表中找到一个字母并以原始大小写返回这些单词(大写/小写) - Python: How to find a letter in a sentence's list of words and return those words in their original case (upper/lower) 如何使用 Python Regex 查找所有首字母为大写的单词 - How to find all words with first letter as upper case using Python Regex 使用Python dict理解按首字母索引单词列表 - Using Python dict comprehension to index list of words by first letter 如何查找单词 - 第一个字母大写,其他字母小写 - How to find a words - First letter will be capital & other will be lower 如何查找包含用户输入的前3个字符的单词 - How to find words which contain the first 3 characters input by a user 查找列表中以某些字母开头的单词 - Find how many words start with certain letter in a list 以两个包含单词的列表作为输入,以形成包含两个单词的元组,每个列表中的一个单词的起始字母相同 - Taking two lists as input that contain words, to form a tuple with two words, one from each list that have the same starting letter of each word (Python)如何将几个字母与整个单词列表进行比较以查找哪些单词按顺序包含搜索的字母? - (Python) How do I compare a few letters to a whole list of words to find, what words contain the searched-for letters in order?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM