簡體   English   中英

嘗試按順序在列表列表中添加重復項

[英]Trying to add duplicates within a list of lists in order

我在一個列表中有兩個單獨的列表。我正在嘗試計算第二個列表中的重復項。 我可以從列表 a 到列表 b,結果是:

count_list = [['about', 1], ['almost', 1], ['apple', 1], ['break', 1], ['Singapore', 1], ['cider', 1], ['up', 1], ['day', 1]]
first_proc_count = [['turn', 1], ['there', 1], ['pear', 1], ['up', 1], ['XXXXXX', 0], ['drink', 1], ['near', 1], ['up', 1]]

for word in first_proc_count:  
    for word2 in count_list:
        if word[0] == word2[0]:
            word[1] = word[1] + word2[1]
            word2[1] = 0  


print(count_list)
print(first_proc_count)

結果 -[['about', 1], ['almost', 1], ['apple', 1], ['break', 1], ['Singapore', 1], ['cider', 1], ['向上', 0], ['天', 1]] -[['轉', 1], ['那里', 1], ['梨', 1], ['向上', 2], ['XXXXXX', 0], ['喝', 1], ['附近', 1], ['向上', 1]]

將單詞“up”添加到第二個列表中,“up”在第一個列表中設置為 0。

但是我在第二個列表中做同樣的事情時遇到了問題,即。 用一個列表。 我知道我應該將循環遞增 1 並查看遞增的循環。 我希望的結果是:

[['轉', 1], ['那里', 1], ['梨', 1], ['向上', 3], ['XXXXXX', 0], ['喝', 1], [ '附近', 1], ['向上', 0]]

我已經嘗試了 += 1 的范圍和長度,但我一無所獲。 第一次在這里提問。 請原諒錯誤的格式。 謝謝。

當前的問題是您正在將列表與自身進行兩次比較。 下面的代碼應該解決這個問題:

count_list = [['about', 1], ['almost', 1], ['apple', 1], ['break', 1], ['Singapore', 1], ['cider', 1], ['up', 1], ['day', 1]]
first_proc_count = [['turn', 1], ['there', 1], ['pear', 1], ['up', 1], ['XXXXXX', 0], ['drink', 1], ['near', 1], ['up', 1]]

for i in range(len(first_proc_count)):
    for word2 in first_proc_count[i + 1:]:
        if first_proc_count[i][0] == word2[0]:
            first_proc_count[i][1] = first_proc_count[i][1] + word2[1]
            word2[1] = 0

print(count_list)
print(first_proc_count)

暫無
暫無

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

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