【问题标题】:list comprehension produces None values [duplicate]列表理解产生无值[重复]
【发布时间】: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


【解决方案1】:

您可以首先在列表推导中使用enumerate 来过滤掉出现元音的索引。然后,您可以使用所有索引的set 差异来找到辅音必须出现的补码。

def my_function(string):
    vowels = [idx for idx, val in enumerate(string) if val.lower() in 'aeiou']
    consts = list(set(range(len(string))) - set(vowels))
    return vowels, consts

>>> my_function('BANANA')
([1, 3, 5], [0, 2, 4])

可以解压得到单独的列表

>>> vowels, consts = my_function('BANANA')
>>> vowels
[1, 3, 5]
>>> consts
[0, 2, 4]

【讨论】:

    猜你喜欢
    • 2020-07-19
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2011-06-15
    • 2013-05-11
    • 2017-12-01
    相关资源
    最近更新 更多