gpt4 book ai didi

Python 列表分组依据

转载 作者:行者123 更新时间:2023-12-02 20:47:48 25 4
gpt4 key购买 nike

我有一个像这样的 python 列表:

Category    Title   ProductId   Rating
'Electronics, Books, Bundles' Lautner e-Reader Cover 161553 4
'Electronics, Books, Bundles' Lautner stand in e-Reader Cover 161552 3
'Electronics, Books, Bundles' Lautner Chocolate NOOK Case 594451 5
'Electronics, Books, Bundles' Oliver e-Reader Cover 161685 1
'Electronics, Books, Covers' Dessin Leather Cover for Nook Color; Nook Tablet Digital Reader 594033 4.3
'Electronics, Books, Covers' Emerson Quote e-Reader Cover 161542 2.8
'Electronics, Books, Covers' Industriell Easel e-Reader Cover 161682 3.7
'Electronics, Books, Covers' Jonathan Adler Book Reader Cover Hd - Elephant 594548 4.9
'Electronics, Scanners, Covers' Lyra Light Front Cover for NOOK eR 161683 4
'Electronics, Scanners, Covers' Nook Tablet Dessin Cover in Marine 161686 3.8
'Electronics, Scanners, Covers' Nook Tablet Horizontal Stand Cover in Red 594202 4.2
'Electronics, Scanners, Covers' Canvas Bella Library Cover 161554 3
'Electronics, Books, Radios' Groovy Protective Stand Cover: Custom Designed for 7-inch NOOK HD 594549 3.8
'Electronics, Books, Radios' Hd Groovy Stand In Blue- Nook 594514 4.1
'Electronics, Books, Radios' Hutton Envelope in Bark 161560 2.9
'Electronics, Books, Radios' Italian Leather-Style Chesterton Cover for NOOK Reader 161561 4

在所有这些列表值中,我想要每个类别中的前 k 个。前 2 名应该给出以下结果:

'Electronics, Books, Bundles'   Lautner Chocolate NOOK Case 594451  5
'Electronics, Books, Bundles' Lautner e-Reader Cover 161553 4
'Electronics, Books, Covers' Jonathan Adler Book Reader Cover Hd - Elephant 594548 4.9
'Electronics, Books, Covers' Dessin Leather Cover for Nook Color; Nook Tablet Digital Reader 594033 4.3
'Electronics, Books, Radios' Hd Groovy Stand In Blue- Nook 594514 4.1
'Electronics, Books, Radios' Italian Leather-Style Chesterton Cover for NOOK Reader 161561 4
'Electronics, Scanners, Covers' Nook Tablet Horizontal Stand Cover in Red 594202 4.2
'Electronics, Scanners, Covers' Lyra Light Front Cover for NOOK eR 161683 4

添加我尝试过的任何东西:

sorted_data = sorted(data, key=operator.itemgetter(1), reverse=True)

k = int(sys.argv[1])
for result in sorted_data[:k]:
print result

在这里,我将“k”作为命令行参数传递给 python 文件。

最佳答案

使用迭代器之类的,可以获得相对高效的性能。注意:这使用标准的 Python 库。

import heapq
import itertools

# group by 'Category'
groups = itertools.groupby(some_list, key=lambda element: element[0])

# take top two of each group based on 'Rating'
top_two_of_each = (heapq.nlargest(2, values, key=lambda value: value[3]) for
_, values in groups)

# flatten the nested iterators
top_two_of_each_flattened = itertools.chain(*top_two_of_each)

# convert iterator into a list
top_two_of_each_flattened_as_list = list(top_two_of_each_flattened)

关于Python 列表分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43568995/

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