python-3.x - 在列表中查找相同值的索引的最快方法
问题描述
我正在尝试优化以下实现,我有 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])
有什么建议么?
解决方案
但是,如果您有一个商品价格列表,那么您已经知道只需删除其中一个价格即可获得这些“不包括一个价格的重复项”。
例如 (*):如果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.
推荐阅读
- java - 无法在 apache jena 上添加新的 owl 文件
- java - 使用 SWIG 包装具有两个双向参数的函数以在 java [foo(char ** strs, unsigned int& size)] 中使用
- excel - 在复制和粘贴值之前从另一个工作簿中的列表中读取大写值
- python - Python多处理队列酸洗错误
- javascript - 为什么我的 div 容器中的元素会消失?
- python - python - 列出,打印
- gstreamer - 使用 libgstvaapi.so 的 gstreamer-vaapi 插件缺少 vaapih265enc
- ruby-on-rails - 添加@到friendly_id slug Ruby on Rails
- r - R中的循环For返回Null(空)值而不是预期
- python - 如何找到列表的最长连续非零子集?