Python函数返回名字和姓氏中的常见字母的列表 [英] Python Function to return a list of common letters in first and last names

查看:468
本文介绍了Python函数返回名字和姓氏中的常见字母的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:不要在功能中使用设置:使用列表返回名字和姓氏(交集)中常用字母的列表提示用户输入名字和姓氏,并使用名字和姓氏调用函数作为参数并打印返回的列表.

Question: DO NOT USE SETS IN YOUR FUNCTION: Uses lists to return a list of the common letters in the first and last names (the intersection) Prompt user for first and last name and call the function with the first and last names as arguments and print the returned list.

我不知道为什么我的程序即使有字母匹配也只打印"No match".有什么帮助!谢谢一堆!

I can't figure out why my program is just printing "No matches" even if there are letter matches. Anything helps! Thanks a bunch!

到目前为止的代码:

import string

def getCommonLetters(text1, text2):
""" Take two strings and return a list of letters common to
    both strings."""
    text1List = text1.split()
    text2List = text2.split()
    for i in range(0, len(text1List)):
        text1List[i] = getCleanText(text1List[i])
    for i in range(0, len(text2List)):
        text2List[i] = getCleanText(text2List[i])

    outList = []
    for letter in text1List:
        if letter in text2List and letter not in outList:
           outList.append(letter)
    return outList

def getCleanText(text):
"""Return letter in lower case stripped of whitespace and
punctuation characters"""
    text = text.lower()

    badCharacters = string.whitespace + string.punctuation
    for character in badCharacters:
        text = text.replace(character, "")
    return text

userText1  = raw_input("Enter your first name: ")
userText2  = raw_input("Enter your last name: ")
result     = getCommonLetters(userText1, userText2)
numMatches = len(result)
if numMatches == 0:
    print "No matches."
else:
    print "Number of matches:", numMatches

for letter in result:
    print letter

推荐答案

尝试一下:

def CommonLetters(s1, s2):
    l1=list(''.join(s1.split()))
    l2=list(''.join(s2.split()))
    return [x for x in l1 if x in l2]

print CommonLetters('Tom','Dom de Tommaso')    

输出:

>>> ['T', 'o', 'm']

这篇关于Python函数返回名字和姓氏中的常见字母的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆