为了账号安全,请及时绑定邮箱和手机立即绑定

如何通过迭代集合中的元素来删除集合中的特定元素?

如何通过迭代集合中的元素来删除集合中的特定元素?

森林海 2022-10-06 19:56:15
所以我有一个表格的元组列表(subject1,relationtype,sobject2),代表关系事实。如果它们都在列表中(subject1,relationtype,sobject2),我想编写一个删除其中一个的方法。(subject2,relationtype,sobject1)这是我尝试过的:def delete_symmetric_relations(A):    A = set(tuple(e) for e in A)    for (s,r,o) in A:        for (s1, r1, o1) in A:            if (s,r,o)==(o1,r1,s1) and (s,r,o) != (s1,r1,o1):                A.remove((s1,r1,o1))    return list(A)print(delete_symmetric_relations(data)) 然后我得到错误: RuntimeError: Set changed size during iteration该方法应该如何工作的示例:假设我们有 list [(1,in_same_numbersystem_as,3),(2,"is_smaller_than",4),(3,in_same_numbersystem_as,1),(2,"is_smaller_than",6)],该方法应该从建议中返回一个[(2,"is_smaller_than",4),(3,in_same_numbersystem_as,1),(2,"is_smaller_than",6)]or [(1,in_same_numbersystem_as,3),(2,"is_smaller_than",4),(2,"is_smaller_than",6)] ,我将代码重写为:def delete_symmetric_relations(A):    somelist = [(s,r,o) for (s,r,o) in A if (o,r,s) not in A]    return somelist但是这段代码删除了所有 (s,r,o) 和 (o,r,s) 但我想至少保留一个。得到:IOPub data rate exceeded.The notebook server will temporarily stop sending outputto the client in order to avoid crashing it.To change this limit, set the config variable`--NotebookApp.iopub_data_rate_limit`因为我的清单非常非常大。那么我该怎么做呢?
查看完整描述

2 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

我最初误解了这个问题。基本概念仍然成立。不要尝试更改您正在循环的列表。相反,制作一个副本以进行变异。然后遍历原始列表。你可以做任何你需要的比较。


def remove_symetric(A):


    B = A

    for (a, b, c) in A:

        if (c,b,a) in B:

            B.remove((c,b,a))


    return B


A = [(0, 1, 3), (0, 1, 3), (0, 2, 3), (0, 1, 4), (5, 1, 3), (0, 7, 3), (0, 7, 3),(3, 1, 0)]

A=remove_symetric(A)

print("Non-duplicate items:")

print(A)

输出:


Non-duplicate items:

[(0, 1, 3), (0, 1, 3), (0, 2, 3), (0, 1, 4), (5, 1, 3), (0, 7, 3), (0, 7, 3)]

原答案:


而不是删除重复项。如果尚未添加,请尝试添加到空白列表。像这样的东西:


def return_unique(A):


    B = []

    for x in A:

       if x not in B:

           B.append(x)

    return B

像这样测试:


A = [(0, 1, 3), (0, 1, 3), (0, 2, 3), (0, 1, 4), (5, 1, 3), (0, 7, 3), (0, 7, 3)]

B = return_unique(A)

print('Non-duplicate items:')

print(B)

Non-duplicate items:

[(0, 1, 3), (0, 2, 3), (0, 1, 4), (5, 1, 3), (0, 7, 3)]


查看完整回答
反对 回复 2022-10-06
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

您可以对列表中的每个元组进行排序并将最终输出传递到集合中将删除重复项


>>> data = [(0,1,7), (5,1,3), (7,1,0), (0,7,1)]  # sample input


>>> data = list(set(map(lambda x: tuple(sorted(x)), data)))

[(1, 3, 5), (0, 1, 7)]

注意:上述解决方案仅在您tuple必须具有唯一的type object. 如果您的元组包含不同type对象的混合,那么您需要将其中的所有元素转换tuple为string类型并将其传递给sorted方法。


>>> data = [(0, 1, 7, 'b'), (5, 1, 3, 'a'), (7, 1, 0, 'b'), (0, 1, 7, 'b')]

>>> list(set(map(lambda x: tuple(sorted(map(str, x))), data)))

[('1', '3', '5', 'a'), ('0', '1', '7', 'b')]


查看完整回答
反对 回复 2022-10-06
  • 2 回答
  • 0 关注
  • 136 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号