【问题标题】:Find an element by inner tuple in a list of a tuple of tuples在元组的元组列表中通过内部元组查找元素
【发布时间】:2020-05-27 20:19:53
【问题描述】:

好的。所以我经历了一些 SO 答案,例如Find an element in a list of tuples in python,但它们似乎并不特定于我的情况。而且我不知道如何在我的问题中使用它们。

假设我有一个元组列表;即列表存储了几个数据点,每个数据点都指向一个笛卡尔点。每个外部元组代表该点的全部数据。这个元组中有一个内部元组,正是这个点。也就是说,让我们取点 (1,2) 并用 5 表示这一点的某些含义。外部元组将是((1,2),5)

嗯,很容易弄清楚如何生成它。但是,我想根据内部元组的值搜索外部元组。这就是我想做的:

for y in range(0, 10):
    for x in range(0, 10):
        if (x, y) in ###:
            print("Found")

或类似的东西。如何做到这一点?


根据@timgen 作为评论发布的建议,这里是一些伪样本数据。
名单将是

selectPointSet = [((9, 2), 1), ((4, 7), 2), ((7, 3), 0), ((5, 0), 0), ((8, 1), 2)]

所以我可能想遍历从 (0,0) 到 (9,9) 的整个点域,如果该点是 selectPointSet 中的点之一,则做一些事情;即如果是 (9, 2), (4, 7), (7, 3), (5, 0) 或 (8, 1)

【问题讨论】:

  • 请举个实际例子。一些示例数据和我们可以使用的预期输出。
  • @timgeb 这是我能做到的。数据中没有更多细节与疑问有关:-(
  • 我只需要样本数据。
  • 到目前为止,我没有样本数据,因为这是一个全新的问题。不过还是让我试试吧。我将其添加为更新

标签: python list tuples


【解决方案1】:

使用您当前的数据结构,您可以这样做:

listTuple = [((1,1),5),((2,3),5)] #dummy list of tuples
for y in range(0, 10): 
    for x in range(0, 10):
        for i in listTuple:#loop through list of tuples
            if (x, y) in listTuple[listTuple.index(i)]:#test to see if (x,y) is in the tuple at this index
                print(str((x,y)) , "Found")

【讨论】:

  • 我确实想到了这一点,但在这种情况下它是一个巨大的层次结构。而且每次都必须通过 listTuple,尽管在另一种情况下也会发生这种情况
【解决方案2】:

你可以使用字典。

temp = [((1,2),3),((2,3),4),((6,7),4)]
newDict = {}

# a dictionary with inner tuple as key
for t in temp:
    newDict[t[0]] = t[1]

for y in range(0, 10):
    for x in range(0, 10):
        if newDict.__contains__((x,y)):
            print("Found")

我希望这是您的要求。

【讨论】:

  • 您正在使用该变量名称隐藏内置名称 dict。你的字典可以简单地用dict(temp) 构造。 has_key 方法已在 Python 3 中删除。
  • 我指的是这个答案:stackoverflow.com/a/56356052/6539635 用于修改答案以解决has_key 问题。现在可能不会出现这种变化。版主必须接受它
【解决方案3】:

从两元素元组中创建一个集合以进行 O(1) 查找。

>>> data = [((1,2),3),((2,3),4),((6,7),4)]
>>> tups = {x[0] for x in data}

现在您可以使用任何您喜欢的元组查询tups

>>> (6, 7) in tups
True
>>> (3, 2) in tups
False

搜索从 0 到 9 的值:

>>> from itertools import product
>>> for x, y in product(range(10), range(10)):
...     if (x, y) in tups:
...         print('found ({}, {})'.format(x, y))
...         
found (1, 2)
found (2, 3)
found (6, 7)

如果您需要保留有关第三个数字的信息(并且data 中的二元素内部元组是唯一的),那么您还可以构造字典而不是集合。

>>> d = dict(data)
>>> d
{(1, 2): 3, (2, 3): 4, (6, 7): 4}
>>> (2, 3) in d
True
>>> d[(2, 3)]
4

【讨论】:

  • 啊哈,我在等最后一次编辑,看来 :-D 必须接受这个
  • 只是一个疑问。 d = dict(data) 复制data,对吗? IE。如果我修改d中的值,它不会影响data,对吧?
  • @AaronJohnSabu 没有复制。但是你不能改变d 中的值,因为元组和整数是不可变的。您可能正在考虑重新分配 d 中的键。在这种情况下,data 保持不变。
猜你喜欢
  • 2015-07-06
  • 2011-01-12
  • 2016-12-19
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 2016-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多