首页 > 解决方案 > 在列表中查找相同值的索引的最快方法

问题描述

我正在尝试优化以下实现,我有 2 个数组:

item= [3,  2,  6, 1,  3,  1,  9,  3]
price=[21, 54, 2, 56, 13, 98, 56, 20]

我需要的是获得一个项目重复的价格(不包括它自己的价格)。

3: [13, 20]
2: []
6: []
1: [98]
3: [21, 20]
1: [56]
9: [56]
3: [21,13]

我目前的解决方案使用 2 个 for 循环:

for i in range(item):
same=[]
    for j in range(item):
        if item[j]==item[i] and j!=i:
            same.append(price[j])

有什么建议么?

标签: python-3.x

解决方案


但是,如果您有一个商品价格列表,那么您已经知道只需删除其中一个价格即可获得这些“不包括一个价格的重复项”。

例如 (*):如果3: [21, 13, 20]您知道“不包括一个价格的重复”是:

3: [13, 20]
3: [21, 20]
3: [21, 13]

因此,您应该能够执行以下操作:

from collections import defaultdict

items = [3,  2,  6, 1,  3,  1,  9,  3]
prices = [21, 54, 2, 56, 13, 98, 56, 20]

item_to_price = defaultdict(list)
for item, price in zip(items, prices):
    item_to_price[item].append(price)

然后你可以很容易地操纵这个dict的值来获得(*):

# To create the result you want for 3:
def single_removed(lst):
    for rmidx in range(len(lst)):
        yield lst[:rmidx] + lst[rmirx+1:]

# For example for 3:
for sr in single_removed(item_to_price[3]):
    print(f'3: {sr}')

# Will give you:
# 3: [13, 20]
# 3: [21, 20]
# 3: [21, 13]
# as wanted.

推荐阅读