【发布时间】:2020-06-08 14:43:11
【问题描述】:
我正在尝试将字符串的元音和常量索引存储在两个列表中,到目前为止,我有以下内容:
def my_function(string):
vowels_index = [] # vowels indices list
const_index = [i if string[i] not in "AEIOU" else vowels_index.append(i) for i in range(len(string))] # constants indices list
const_index 中存在一些 None 值:
>>> string = "BANANA"
>>> const_index = [i if string[i] not in "AEIOU" else vowels_index.append(i) for i in range(len(string))]
>>> const_index
[0, None, 2, None, 4, None]
>>>
有没有更好的方法来查找这两个列表?
【问题讨论】:
-
不要那样做。
append不返回任何内容,因此您会看到None。您必须对元音或其他方式有新的理解。 -
使用简单的 for 循环而不是列表理解,稍后感谢我,但正如@Austin 指出的那样,您正在添加 None 返回时 else
标签: python string list list-comprehension