Python列表组由

时间:2017-04-23 08:32:05

标签: python list group-by

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

child_process.fork

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

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

添加我尝试的任何内容:

'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

这里我将'k'作为命令行参数传递给python文件。

4 个答案:

答案 0 :(得分:1)

这可能就是您所需要的:

data = ''''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'''


groups = [item.split("' ") for item in data.split('\n')]
grouped_data = {}

for group in groups:
    item = [group[1].strip()]
    group = group[0].strip("'")
    if group not in grouped_data:
        grouped_data[group] = item
    else:
        grouped_data[group] += item

def topN(data, n):
    data = [item.split() for item in data]
    data = sorted(data, key=lambda x: float(x[-1]), reverse=True)[:n]
    data = [' '.join(item) for item in data]
    return data

result = {}
for k, v in grouped_data.items():
    result[k] = topN(v, 2)

final_result = [': '.join([group1, item1]) for group1, value1 in result.items() for item1 in value1]

答案 1 :(得分:1)

可能不是一个有效但可理解的解决方案:

你想要每个元素的最高结果,所以首先我们需要识别元素。我们通过在'拆分来实现这一点,因为这是最简单的指标,第一个'中的空字符串将被丢弃([1:])。

separated = [element.split("'")[1:] for element in data]

由于我们对第一个字符串标识的项目感兴趣,因此字典似乎是一个合适的数据结构。

from collections import defaultdict
data_dict = defaultdict(list)
for line in separated:
    data_dict[line[0]].append(line)

现在我们有一个很好的格式,可以对dictonary进行排序。

表示data_dict.keys()中的键:     data_dict [key] .sort(key = lambda key_string:key_string.split()[ - 1],reverse = True)

从这本字典中可以很容易地重现我们的结果:

k = 2
results = []
for key in data_dict.keys():
    results.extend(data_dict[key][:k])

关键是使用合适的数据结构,这里是字典。 这是简短的解决方案:

# make a dict 
from collections import defaultdict
data_dict = defaultdict(list)
for line in data:
    data_dict[line.split("'")[1]].append(line)


# function working on the dict:
def top_results(data_dict, k):
    results = []
    for key in data_dict.keys():
        results.extend(data_dict[key][:k])
    return results

但是更适合继续使用字典而不是返回不合适的列表。

总结:

  1. 确定合适的数据结构,dict适合。
  2. 获取您的密钥,split("'")适用于此
  3. 以漂亮的格式重新整理您的数据
  4. 使用list.sort对列表进行排序。需要key,此处我们只使用最后一个单词str.split()[-1],因为这是您的排名。

答案 2 :(得分:1)

使用迭代器等,您可以获得相对高效的性能。注意:这使用标准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)

答案 3 :(得分:0)

假设您正在寻找与此类似的东西。 This is the code.

你的清单太长了。这就是我在这里使用一个简单列表的原因。 This is the result that I got.