【问题标题】:Index of incomplete tuple in list of tuples元组列表中不完整元组的索引
【发布时间】:2017-01-02 16:51:52
【问题描述】:

这是我的问题:

我有一个元组列表 (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)

【问题讨论】:

  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只会在发布者已经尝试自己解决问题时提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出以及您实际获得的输出(控制台输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask

标签: python list python-3.x search indexing


【解决方案1】:

你可以使用filter():

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

【讨论】:

  • 这将返回列表中的第一个 元素,而不是索引(尽管这似乎是 OP 试图做的,所以它是模棱两可的)。此外,最好使用next,而不是将整个结果放入列表中,然后使用pop
  • @juanpa.arrivillaga index = my_list.index(item) 返回索引,我使用 list 而不是 next 只是为了编写适用于两个 Python 版本的解决方案。我更新了它以使用下一个,因为 Python 3 在这个问题中被标记。谢谢!
  • 非常感谢您的回答,我认为这是最好的方法,但我收到“StopIteration”错误,我不知道为什么
  • 如果您的列表中没有匹配的元素,您将收到StopIteration 错误。
  • 尝试使用数字很好,但是在我想使用它的上下文中使用它时,它似乎无法找到它正在寻找的东西
【解决方案2】:

这是使用 生成器表达式 的一种方法,它通过在 gen 上调用 next 返回第一个匹配元组的索引。 exp。 enumerate 返回每​​个元组的索引和元组本身:

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

如果没有找到包含给定值的元组,则会出现错误。

另一方面,如果您想收集所有符合条件的元组,可以使用列表推导式。

【讨论】:

    【解决方案3】:

    这是一种容错方式。注意,如果没有找到任何匹配的元组,它会返回 -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
    

    【讨论】:

      猜你喜欢
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 2015-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多