当比较两个不同列表中的元组时,如何解决“TypeError:列表索引必须是整数或切片,而不是元组”?

2024-05-16 10:16:03 发布

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

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.

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

这就是没有傻瓜的样子

img

这就是全面主义者的样子

img

错误是什么样子的

img

如何解决这个错误?在


Tags: thenoin列表as错误notlist
1条回答
网友
1楼 · 发布于 2024-05-16 10:16:03

这个错误是由这样一个事实引起的,即x是一个元组,并且不能将一个元组用作totalist的索引。必须是整数。在

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

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"

在这个例子中,输出是

^{pr2}$

相关问题 更多 >