在 Python 中查找以特定字母开头的列表元素

pythonserver side programmingprogramming更新于 2026/1/22 18:20:17

在本文中,我们将从列表中查找以特定字母开头的所有元素。

使用索引和 lower

我们使用 lower 函数,以便稍后的测试可以与列表中元素的首字母匹配,而不考虑大小写。然后我们使用 0 处的索引,以便将列表中元素的首字母与测试字母进行比较。

示例

listA = ['Mon', 'Tue', 'Wed', 'Thu']
# 带字母测试
test = 'T'
# 打印原始列表
print("Given list\n " ,listA)
# 使用 lower 和 idx
res = [idx for idx in listA if idx[0].lower() == test.lower()]
# 打印结果
print("List elements starting with matching letter:\n " ,res)

输出

运行上述代码得到以下结果 −

Given list
['Mon', 'Tue', 'Wed', 'Thu']
List elements starting with matching letter:
['Tue', 'Thu']

使用 startswith

这是一个非常直接的方法,我们使用函数 startswith。如果元素以测试字母开头,则此函数返回 true,否则返回 false。

示例

listA = ['Mon', 'Tue', 'Wed', 'Thu']
# 测试字母
test = 'T'
# 打印原始列表
print("Given list\n " ,listA)
# 使用 startswith
res = [idx for idx in listA if idx.lower().startswith(test.lower())]
# 打印结果
print("List elements starting with matching letter:\n " ,res)

输出

运行上述代码得到以下结果 −

Given list
['Mon', 'Tue', 'Wed', 'Thu']
List elements starting with matching letter:
['Tue', 'Thu']

相关文章


有用资源