简体   繁体   中英

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. 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']

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM