在单词列表中查找最后两个字符

时间:2018-10-25 17:30:04

标签: python-3.x

我想知道如何创建一个函数,以将单词的最后一个返回到单词列表中的每个单词的字符。这就是我的想法:

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

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


print(two(mylist))

我要打印的是“ lorele”

3 个答案:

答案 0 :(得分:1)

您可以使用列表推导或生成器表达式并使用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,并编辑了您的问题以反映该问题。

答案 1 :(得分:0)

列表理解是你的朋友

>>> a=["hello",'world','how','are','you!']
>>> '12345'[-2:]
'45'
>>> b=[mine[-2:] for mine in a]
>>> b
['lo', 'ld', 'ow', 're', 'u!']
>>> "".join(b)
'loldowreu!'

答案 2 :(得分:0)

首先,您不能使用保留字作为变量名。

使用您的代码:

print(''.join([s[-2:] for s in ["Hello","there","people"]]))

具有列表理解:

{{1}}