簡體   English   中英

Python從兩個列表中刪除列表項的第一次出現

[英]Python Drop first occurrence of list Item from two lists

我正在使用python取消模子的骰子滾軸。 我已經創建了模具卷並將它們存儲在列表中。 0是第一組骰子卷, 1是第二組骰子卷。

{0: [4,2,3,2], 1: [2,3,6]}

python腳本會在兩個列表中找到每個唯一編號的第一個匹配編號,然后將其從列表中刪除。

結果之后:

{0: [4,2], 1: [6]}

我似乎找不到正確的方法來實現這一目標。 我已經研究過itertoolsfind_first但是我想不出一種使它起作用的方法。

有人有提示嗎?

這里嘗試:

dct = {0: [4, 2, 3, 2], 1: [2, 3, 6]}
new_dct = dct[0].copy()
for i in new_dct:
    if i in dct[1]:
        dct[0].remove(i)
        dct[1].remove(i)
print(dct)

更新:

如果您需要可以更改

new_dct = dct[0].copy()
for i in new_dct:

for i in dct[0][:]:

我認為這對您有幫助:

l0_ = [4,2,3,2]
l0 = list(l0_) # this is needed to make a deep copy of l0_
l1 = [2,3,6]
for i in l0_:
    if i in l1:
        l0.remove(i)
        l1.remove(i)
res = {0:l0, 1:l1}
res

如果您不想考慮重復,可以先將列表轉換為集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM