【问题标题】:How to find a duplicate in a list and perform different calculation for each instance of duplicate found?如何在列表中查找重复项并对找到的每个重复项执行不同的计算?
【发布时间】:2020-06-10 22:13:31
【问题描述】:
a_list = [1, 2, 3, 1, 2, 3, 1, 2, 3]

我想遍历a_list 并查找重复项。如果找到重复项,我想对该重复项进行计算。如果发现同一实例的另一个副本,则应执行不同的计算。

例如:

开始迭代a_list:

1, 2, 3, 1 [Instance of duplicate 1 found - Perform 1+1 on instance]

继续迭代...

1, 2, 3, 1, 2 [Instance of duplicate 2 found - Perform 2+2 on instance]

继续迭代...

1, 2, 3, 1, 2, 3 [Instance of duplicate 3 found - Perform 3+3 on instance]

继续迭代...

1, 2, 3, 1, 2, 3, 1 [Second instance of duplicate 1 found - Perform 1+1+1 on instance]

继续迭代...

1, 2, 3, 1, 2, 3, 1, 2 [Second instance of duplicate 2 found - Perform 2+2+2 on instance]

继续迭代...

1, 2, 3, 1, 2, 3, 1, 2, 3 [Second instance of duplicate 3 found - Perform 3+3+3 on instance]

完成后会创建一个包含所有计算的新列表:

new_list = [1, 2, 3, 2, 4, 6, 3, 6, 9]

有人可以向我解释如何查找重复项以及计算这些重复项的实例,以便我可以对重复项的每个新实例执行不同的计算吗?

【问题讨论】:

标签: python list loops duplicates


【解决方案1】:

我会使用字典来跟踪使用了哪些值以及使用的次数。

a_list = [1, 2, 3, 1, 2, 3, 1, 2, 3]
tracking_dict = {}
out_list = []
for item in a_list:
    # checks if item has been seen before
    if item in tracking_dict:
        # add the number as many times as it has been seen
        out_list.append(item + item * tracking_dict[item])
        # since you've seen the number, increase the count by 1
        tracking_dict[item] += 1
    else:
        # add it to the output list as-is
        out_list.append(item)
        # the item is new to this list
        tracking_dict[item] = 1
print(out_list)

希望这会有所帮助!

【讨论】:

  • 我建议你阅读 dict 方法setdefault。它可以用来减少你的条件
  • @Tomerikoo 或collections.defaultdict,类似的想法。
【解决方案2】:

这是the answer by @Alexander 的调整版本,供粉丝collections.defauldict 使用。

import collections as colls

a_list = [1, 2, 3, 1, 2, 3, 1, 2, 3]
d = colls.defaultdict(int)
result = []

for val in a_list:
    d[val] += val
    result.append(d[val])

print(result)

输出:

[1, 2, 3, 2, 4, 6, 3, 6, 9]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2013-02-21
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多