尝试按顺序在列表列表中添加重复项
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], ['up', 0], ['day', 1]]
-[['turn', 1], ['there', 1], ['pear', 1], ['up', 2], ['XXXXXX', 0 ], ['drink', 1], ['near', 1], ['up', 1]]
将单词“up”添加到第二个列表,“up”在第一个列表中设置为 0。
但是我在第二个列表中做同样的事情时遇到了问题,即。用一个列表。我知道我应该将循环递增 1 并查看递增的循环。我希望的结果是:
[['turn', 1], ['there', 1], ['pear', 1], ['up', 3], ['XXXXXX', 0], ['drink', 1], ['near', 1], ['up', 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)
我在一个列表中有两个单独的列表。我正在尝试计算第二个列表中的重复项。我可以从列表 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], ['up', 0], ['day', 1]] -[['turn', 1], ['there', 1], ['pear', 1], ['up', 2], ['XXXXXX', 0 ], ['drink', 1], ['near', 1], ['up', 1]]
将单词“up”添加到第二个列表,“up”在第一个列表中设置为 0。
但是我在第二个列表中做同样的事情时遇到了问题,即。用一个列表。我知道我应该将循环递增 1 并查看递增的循环。我希望的结果是:
[['turn', 1], ['there', 1], ['pear', 1], ['up', 3], ['XXXXXX', 0], ['drink', 1], ['near', 1], ['up', 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)