返回元组中值的索引号/顺序

2024-05-23 21:54:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份清单:

my_tuple = [('apple', 'red'), ('lime', 'green'), ('banana', 'yellow'), ('blueberry', 'blue')]

我试图获取列表中给定值的索引号/顺序

范例

我想得到“lime”的索引,它是1。或者“蓝莓”的指数是4

我尝试使用:

my_tuple.index('apple') 
my_tuple.index('red') 

但是我的语法不正确

我希望能够从任一元素的输入中获得索引号。例如index('apple')index('red')都将返回0

例)

>>>my_tuple.index('apple')
 0
>>>my_tuple.index('red')
 0

这可能吗?或者我需要输入第一个和第二个值才能获得索引号吗


Tags: apple列表index顺序mygreenbluered
3条回答

我建议您使用enumerate并遍历您的列表。如果想要的项位于元组中,则返回该索引

lst = [('apple', 'red'), ('lime', 'green'), ('banana', 'yellow'), ('blueberry', 'blue')]
def look(my_tuple,wanted):
    for count,food in enumerate(my_tuple):
        if wanted in food:
            return count
print(look(lst,'apple'))

输出

0

您可以这样做:

def index_of(values, value):
    return next((i for i, tupl in enumerate(values) if value in tupl), -1)
    
print(index_of(my_tuple, 'apple'))   # 0
print(index_of(my_tuple, 'red'))     # 0
print(index_of(my_tuple, 'lime'))    # 1
print(index_of(my_tuple, 'banana'))  # 2
print(index_of(my_tuple, 'monkey'))  # -1

这里有另一种使用enumerate()的方法。它创建包含该值的元素的索引列表,然后返回第一个(可能是唯一的)元素的索引:

def value_index(values, value):
    try:
       return [i for i, group in enumerate(values) if value in group][0]
    except IndexError:
        pass
    raise ValueError(f'{value!r} not found')

my_tuple = [('apple', 'red'), ('lime', 'green'), ('banana', 'yellow'),
            ('blueberry', 'blue')]

print(value_index(my_tuple, 'apple'))   # -> 0
print(value_index(my_tuple, 'yellow'))  # -> 2
print(value_index(my_tuple, 'purple'))  # -> ValueError: 'purple' not found

相关问题 更多 >