首页 > 解决方案 > Find last two characters in a list of words

问题描述

I wonder how I could make a function that returns the last to characters of each of the words in a list of words. Here's what I am thinking:

mylist = ["Hello","there","people"]

def two(s):
    for element in s:
        letters = element[2:-1]
    return(letters)


print(two(mylist))

What I want printed out is "lorele"

标签: python-3.x

解决方案


您可以使用列表推导或生成器表达式来做到这一点,并使用join

mylist = ["Hello","there","people"]

def two(s):
    return ''.join(i[-2:] for i in s)

>>> two(mylist)
'lorele'

或者,要修复几乎可以正常工作的代码:

def two(s):
    # Initialize letters as an empty string:
    letters = ''
    # Append last two letters for each element:
    for element in s:
        # Proper indexing is [-2:], which takes from the second to last character to the end of each element
        letters += element[-2:]
    return(letters)

注意:不要list用作变量名,因为它掩盖了 python 的内置类型。我在上面的示例中将其更改为mylist,并编辑了您的问题以反映这一点。


推荐阅读