如何根据用于排序的列仅保留列表中特定数量的元素?

时间:2018-05-18 20:02:09

标签: python list sorting

好的,我有一个包含以下结构的列表:

List1=[[a,b,c,data1,e],
[a,b,c,data2,e],
[a,b,c,data3,e],
[a,b,c,data1,e],
[a,b,c,data2,e],
[a,b,c,data3,e],
[a,b,c,data1,e],
[a,b,c,data1,e],
[a,b,c,data2,e],
[a,b,c,data3,e]]

现在我使用以下方式对列表进行了排序:

List1.sort(key=lambda elem: elem[3])

产生的输出是:

List1=[[a,b,c,data1,e],
    [a,b,c,data1,e],
    [a,b,c,data1,e],
    [a,b,c,data1,e],
    [a,b,c,data2,e],
    [a,b,c,data2,e],
    [a,b,c,data2,e],
    [a,b,c,data3,e],
    [a,b,c,data3,e],
    [a,b,c,data3,e]]

我想要实现的是每个不同的数据值只有2个元素,即:

List1=[[a,b,c,data1,e],
    [a,b,c,data1,e],
    [a,b,c,data2,e],
    [a,b,c,data2,e],
    [a,b,c,data3,e],
    [a,b,c,data3,e]]

3 个答案:

答案 0 :(得分:0)

这样做你想要的吗?

List1 = [["a", "b", "c", "data1", "e"],
         ["a", "b", "c", "data2", "e"],
         ["a", "b", "c", "data3", "e"],
         ["a", "b", "c", "data1", "e"],
         ["a", "b", "c", "data2", "e"],
         ["a", "b", "c", "data3", "e"],
         ["a", "b", "c", "data1", "e"],
         ["a", "b", "c", "data1", "e"],
         ["a", "b", "c", "data2", "e"],
         ["a", "b", "c", "data3", "e"]]
def group(l,n,key=lambda e:e):
    l = sorted(l,key=key)
    out = l[:n]
    for line in l:
        if key(line) != key(out[-n]):
            out.append(line)
    return out


print(group(List1,2,lambda e:e[3]))

打印:

[['a', 'b', 'c', 'data1', 'e'],
 ['a', 'b', 'c', 'data1', 'e'],
 ['a', 'b', 'c', 'data2', 'e'],
 ['a', 'b', 'c', 'data2', 'e'],
 ['a', 'b', 'c', 'data3', 'e'],
 ['a', 'b', 'c', 'data3', 'e']]

答案 1 :(得分:0)

我不知道我是否理解你是对的,但试试这个:

a = 1
b = 2
c = 3
data1 = 4
data2 = 5
data3 = 6
e = 7

list_1 = [[a, b, c, data1, e],
          [a, b, c, data1, e],
          [a, b, c, data1, e],
          [a, b, c, data1, e],
          [a, b, c, data2, e],
          [a, b, c, data2, e],
          [a, b, c, data2, e],
          [a, b, c, data3, e],
          [a, b, c, data3, e],
          [a, b, c, data3, e]]

list_1.sort(key=lambda elem: elem[3])
for x, _list in enumerate(list_1):
    if x % 2 == 0:
        del list_1[x]

print(list_1)

答案 2 :(得分:0)

from itertools import groupby, islice, chain
num_to_keep = 2
d = [list(islice(group, num_to_keep)) 
     for key, group in groupby(List1, lambda x: x[3])]
list(chain(*d))

相同的代码扩展了解释

# Group by data
grouped = groupby(List1, lambda x: x[3])
# Keep only the first 2 of each distinct value of data
num_to_keep = 2
d = [list(islice(group, num_to_keep)) for key, group in grouped]
# Flatten list
list(chain(*d))

请注意,代码使前两行保持相同的“data”值。但是,其他条目可能具有不同的值。您没有指定如何从中选择2行。此外,List1应根据您在运行代码之前用于对行进行分组的条目“data”进行排序。