繁体   English   中英

如何在我的列表理解中使用 else 语句?

[英]How can I use an else statement in my list comprehension?

我知道有很多关于列表理解的问题,但我似乎找不到适合我的问题的问题。

我只想返回字符串列表中一个特定字符的索引。

char_list = ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

def get_index(c, char_list):
    return [index for index in range(len(char_list)) if c == char_list[index]]

get_index('r', char_list)
# This returns [9] which is what I want. 

前面的列表理解可以做到这一点,但我想在其中编写一个 else 语句,如果传入的字符串不存在于列表中,则返回 [-1]。

我看过这个问题( 如果在列表理解中),它提到了一个我试图在这里写出的解决方案:

def get_index(c, char_list):
    return [index if c == char_list[index] else -1 for index in range(len(char_list))]
    
get_index(';', char_list)
# This returns a list equal to the length of char_list 
# returns [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
# The else statement before -1 loops through the entire list and makes a list equal in length


# I want to just return [-1].

如果我将 else 语句放在列表理解的最后,它会引发和错误。

如何在我的列表推导式中放置一个 else 语句,以便在传入的字符不存在于列表中时返回 [-1],如果字符存在于列表中则返回 [index]。 这可能吗?

这并没有考虑到列表中可能存在多个特定字符的计数。 所以在某些方面,这样做有点愚蠢,但我对练习列表理解很感兴趣

你为什么做这个? 有一个built-in函数可以在名为index的列表中查找元素的index

char_list = ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
char_list.index('r') -> 9

如果没有匹配项,您的列表推导会生成一个空列表——因此您的函数只需要返回[-1]代替空列表,而不是修改生成列表的方式。 or运算符是一种返回“默认值”代替假值(如空列表)的简单方法:

>>> def get_index(c, char_list):
...     return [index for index in range(len(char_list)) if c == char_list[index]] or [-1]
...
>>> get_index('r', char_list)
[9]
>>> get_index(';', char_list)
[-1]

我不建议使用列表理解,因为列表在这里没有用,所以使用带有if语句的.index方法来获取输出 -

char_list = ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

def get_index(c, char_list):
    if c in char_list:
        return char_list.index(c)
    return -1

a = get_index('r', char_list)
print(a)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM