python - 如何过滤以任何元音开头的字符串?[Python]
问题描述
字符串是“香蕉”。我已经创建了所有子字符串,现在想要过滤那些以元音开头或不以元音开头的子字符串。我想使用任何操作但不知道如何使用它。
l = ['', 'an', 'anan', 'na', 'ana', 'n', 'a', 'anana', 'ba', 'b', 'ban', 'nan', 'banan', 'banana', 'nana', 'bana']
vowels = 'aeiou'
for word in l:
if word.startswith( any(vowels)): #this gives error
print("this word starts with vowel")
print(word)
解决方案
您可以使用集合来表示vowels
而不是单个字符串,因此查找时间是O(1)
而不是O(n)
,基本上它应该快一点:
words = ['', 'an', 'anan', 'na', 'ana', 'n', 'a', 'anana', 'ba', 'b', 'ban', 'nan', 'banan', 'banana', 'nana', 'bana']
vowels = {'a', 'e', 'i', 'o', 'u'}
for w in words:
if len(w) > 0 and w[0] in vowels:
print(f'"{w}" starts with a vowel')
输出:
"an" starts with a vowel
"anan" starts with a vowel
"ana" starts with a vowel
"a" starts with a vowel
"anana" starts with a vowel
推荐阅读
- android - 以编程方式更改 ListView 项目背景颜色
- node.js - Mock network requests and validate sent request
- cloud-foundry - PCF Dev 与 CF CLI 不兼容
- datatable - 在 Angular 7 中实现数据表
- java - 如何使用模式或匹配器替换字符串中的模式?
- vuejs2 - 如何使用带有分隔文件的 Vue 组件?(TS/HTML/SCSS)
- python - 带有重复键的 Numpy“内部连接”
- c++ - 用 C++ 类实现数组属性
- php - 如何在无需选择项目并单击输入的情况下检索记录
- ios - 如何在 appdelegate 中找到控制器