gpt4 book ai didi

javascript - 识别项目组合的最快方法

转载 作者:行者123 更新时间:2023-12-02 18:04:51 26 4
gpt4 key购买 nike

我正在尝试找出一种方法来识别从订单列表中一起订购的商品的组合(订单由订单 ID 给出)及其数量。例如,在下面的列表中,平板电脑和笔记本电脑一起订购了两次。

 ID    ITEM  
==== =====
1 Phone
1 Mp3 Player
2 Mp3 Player
2 headphone
2 laptop
2 tablet
3 tablet
3 laptop

以下是不同的组合(一次只取 2 个)及其计数:

Phone, Mp3 player - count:1
Mp3 player, headphone - count:1
Mp3 player, laptop - count:1
Mp3 player, tablet - count:1
headphone, laptop - count:1
headphone, tablet - count:1
tablet, laptop - count:2

如何在 VB.net/python/javascript 中进行编程而不需要连续循环?

*(提前致歉,因为我对编码和堆栈溢出都不熟悉)

最佳答案

我明白你在做什么,尽管你指定得相当糟糕。您正在执行groupby操作(基于ID),然后执行组合具有相同ID的类似元素的操作。

在Python中:

li = [(1,'Phone'),(1,'MP3 Player'),(2,'MP3 Player'),(2,'headphone'),(2,'laptop'),(2,'tablet'),(3,'tablet'),(3,'laptop')]

from itertools import groupby, combinations

[list(combinations(g,2)) for _,g in groupby(li,lambda x: x[0])]
Out[10]:
[[((1, 'Phone'), (1, 'MP3 Player'))],
[((2, 'MP3 Player'), (2, 'headphone')),
((2, 'MP3 Player'), (2, 'laptop')),
((2, 'MP3 Player'), (2, 'tablet')),
((2, 'headphone'), (2, 'laptop')),
((2, 'headphone'), (2, 'tablet')),
((2, 'laptop'), (2, 'tablet'))],
[((3, 'tablet'), (3, 'laptop'))]]

如果您想以更易于阅读的格式打印它,就像您的输出一样,请执行以下操作:

output = [list(combinations(g,2)) for _,g in groupby(li,lambda x: x[0])]
for id_ in output:
for combo in id_:
print([x[1] for x in combo])

['Phone', 'MP3 Player']
['MP3 Player', 'headphone']
['MP3 Player', 'laptop']
['MP3 Player', 'tablet']
['headphone', 'laptop']
['headphone', 'tablet']
['laptop', 'tablet']
['tablet', 'laptop']

或者,精确格式化,

for id_ in output:
for combo in id_:
print('{}, {}'.format(*[x[1] for x in combo]))

Phone, MP3 Player
MP3 Player, headphone
MP3 Player, laptop
MP3 Player, tablet
headphone, laptop
headphone, tablet
laptop, tablet
tablet, laptop

关于javascript - 识别项目组合的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20185859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com