元组列表中不完全元组的索引

2024-04-19 12:28:45 发布

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

我的问题是:

我有一个元组列表(a,b,c),我想找到以给定的'a'和'b'开头的第一个元组的索引。你知道吗

示例:

列表=[(1,2,3),(3,4,5),(5,6,7)]

我想要,给定a=1,b=2,返回0(索引(1,2,3))

我找到了一个解决方案,但效率很低:

index0(list)  # returns a list of all first elements in tuples
index1(list)  # returns a list of all second elements in tuples
try:
    i = index0.index(a)
    j = index1.index(b)
    if i == j:
          print(i)

Tags: ofin示例列表indexelementsall解决方案
3条回答

您可以使用^{}

try:
    item = next(filter(lambda item: item[0:2] == (a, b), my_list))
    index = my_list.index(item)
except StopIteration:
    print("No matching item")  # Or for example: index = -1

输出:

>>> my_list = [(1,2,3), (3,4,5), (5,6,7)]
>>> 
>>> a, b = 5, 6
>>> 
>>> item = next(filter(lambda item: item[0:2] == (a, b), my_list))
>>> item
(5, 6, 7)
>>> 
>>> index = my_list.index(item)
>>> index
2

使用生成器表达式可以通过调用gen.exp上的next来返回第一个匹配元组的索引。^{}返回每个元组的索引和元组本身:

t = [(1,2,3), (3,4,5), (5,6,7)]
a = 1
b = 2
val = next(ind for ind, (i, j, _) in enumerate(t) if i==a and j==b)
print(val)
# 0

如果找不到包含给定值的元组,则会出现错误。你知道吗

另一方面,如果要收集所有符合条件的元组,可以使用列表理解。你知道吗

这是一种容错方法。注意,如果找不到任何匹配的元组,则返回-1:

In [3]: def find_startswith(tuples, a, b):
   ...:     for i, t in enumerate(tuples):
   ...:         try:
   ...:             f, s, *rest = t
   ...:             if f == a and s == b:
   ...:                 return i
   ...:         except ValueError as e:
   ...:             continue
   ...:     else:
   ...:         return -1
   ...:
   ...:

In [4]: x
Out[4]: [(1, 2, 3), (3, 4, 5), (5, 6, 7)]

In [5]: find_startswith(x, 1,2)
Out[5]: 0

In [6]: find_startswith(x, 3, 2)
Out[6]: -1

In [7]: find_startswith(x, 3, 4)
Out[7]: 1

In [8]: find_startswith(x, 4, 5)
Out[8]: -1

In [9]: find_startswith(x, 5, 6)
Out[9]: 2

相关问题 更多 >