亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過迭代集合中的元素來刪除集合中的特定元素?

如何通過迭代集合中的元素來刪除集合中的特定元素?

森林海 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個贊

我最初誤解了這個問題?;靖拍钊匀怀闪ⅰ2灰獓L試更改您正在循環的列表。相反,制作一個副本以進行變異。然后遍歷原始列表。你可以做任何你需要的比較。


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 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號