python-3.x - 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"
解决方案
您可以使用列表推导或生成器表达式来做到这一点,并使用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
,并编辑了您的问题以反映这一点。
推荐阅读
- javascript - 如何使用 Jquery 在 Angular 5 上触发点击事件
- c# - 如何在继承 DialogContainer 的类中进行依赖注入?机器人框架 v4
- html - 自定义 checkobx 中的自定义刻度线未显示
- applescript - 从 Applescript 中的多个列表选择返回结果
- excel - 创建多数值列表
- php - 使用ajax提交html表单
- arrays - 如何查找与另一个数组中的另一个值相关联的一个数组的值
- android - 自定义 StartActivity 需要很长时间才能加载新的 Activity
- java - java.util.InputMismatchException 在 GeeksForGeeks 上运行时,在本地运行良好
- javascript - 开玩笑测试失败“未定义窗口”