根据未知数量的子列表中的事件获取列表

时间:2011-09-12 21:49:41

标签: python list

我正在寻找一种方法,将包含列表(下面为a)的列表放入一个列表(下面为b)中,其中包含两个条件:

  1. 新列表(b)的顺序基于a中某些列表中值的发生次数。
  2. 一个值只能出现一次
  3. 基本上将a转换为b

    a = [[1,2,3,4], [2,3,4], [4,5,6]]
    # value 4 occurs 3 times in list a and gets first position
    # value 2 occurs 2 times in list a and get second position and so on...
    b = [4,2,3,1,5,6]
    

    我认为可以用set和一些列表魔术来做到这一点。但是当a可以包含任意数量的列表时,无法理解它。 a列表是根据用户输入创建的(我猜它可以包含1到20个列表,每个列表中有200-300个项目。)

    我尝试使用[set(l) for l in a]一行,但不知道如何执行set(l) & set(l)....来获取所有匹配的项目。

    是否可以在子列表时间内没有for循环迭代子列表计数*项目?

4 个答案:

答案 0 :(得分:4)

我认为这可能是你最接近的地方:

from collections import defaultdict

d = defaultdict(int)

for sub in outer:
  for val in sub:
    d[val] += 1

print sorted(d.keys(), key=lambda k: d[k], reverse = True)
# Output: [4, 2, 3, 1, 5, 6]

有可能出现相同次数的元素顺序不确定 - d.keys()的输出不是有序的。

答案 1 :(得分:1)

试试这个 -

a = [[1,2,3,4], [2,3,4], [4,5,6]]
s = set()
for l in a:
    s.update(l)
print s 
#set([1, 2, 3, 4, 5, 6])
b = list(s)

这会将每个列表添加到集合中,这将为您提供所有列表中所有元素的唯一集合。如果这就是你想要的。

编辑。要保留原始列表中元素的顺序,不能使用集。

a = [[1,2,3,4], [2,3,4], [4,5,6]]
b = []
for l in a:
    for i in l:
        if not i in b:
            b.append(i)
print b
#[1,2,3,4,5,6] - The same order as the set in this case, since thats the order they appear in the list

答案 2 :(得分:1)

import itertools
all_items = set(itertools.chain(*a))
b = sorted(all_items, key = lambda y: -sum(x.count(y) for x in a))

答案 3 :(得分:1)

import itertools
from collections import defaultdict

def list_by_count(lists):
    data_stream = itertools.chain.from_iterable(lists)
    counts = defaultdict(int)
    for item in data_stream:
        counts[item] += 1
    return [item for (item, count) in 
            sorted(counts.items(), key=lambda x: (-x[1], x[0]))]

在排序键中使用x [0]可确保具有相同计数的项目也具有某种顺序。