【问题标题】:How to solve " TypeError: list indices must be integers or slices, not tuple " when comparing tuples in two different lists?比较两个不同列表中的元组时,如何解决“TypeError: list indices must be integers or slices, not tuple”?
【发布时间】:2018-04-29 07:24:42
【问题描述】:
for x in no_dupes: #looks at tuple in list 
    if x != totallist[x]: #checks when a tuple in no_dupes is not in totallist 
        return "The graph violates the STC" #ends the function, because as soon as one tuple in no_dupes isn't in totallist, the graph violats the STC.

我想将一个列表(在列表 no_dupes 中)的所有元组与另一个列表(totallist)进行比较,以查看 no_dupes 中的列表的元组是否在 totallist 中

这就是 no_dupes 的样子

这就是totallist的样子

错误的样子

如何解决这个错误?

【问题讨论】:

  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。
  • 您不能用元组索引列表中的项目。元组可以用作字典键。你试过x in totallist吗?

标签: python list tuples typeerror networkx


【解决方案1】:

这个错误是由于 x 是一个元组并且您不能使用元组作为 totallist 的索引而引起的。这必须是一个整数。

如果您通过循环遍历两个列表直接比较元组,则可以避免该问题。

no_dupes = [(1,2), (3,4), (5,6)]
totallist = [(8,9), (7,8), (6,7), (5,6), (4,5), (3,4), (2,3), (1,2)]

for tup in no_dupes:
    found = False;
    for other_tup in totallist:
        if tup == other_tup:
            found = True
            break
    if found:
        print "Tuple", str(tup), "was found"
    else:
        print "Tuple", str(tup), "was not found"

在这个例子中,输出是

Tuple (1, 2) was found
Tuple (3, 4) was found
Tuple (5, 6) was found

【讨论】:

    猜你喜欢
    • 2022-08-17
    • 2022-11-16
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    相关资源
    最近更新 更多