如何从另一个列表列表中的条件项生成列表列表

时间:2015-05-16 03:34:42

标签: python list sorting iterator

我有一个列表列表,我正在尝试从第一个列表列表中的特定项目中创建另一个列表列表

listOne = [[1,1,9,9],[1,4,9,6],[2,1,12,12]]
listTwo = []

对于位置02中具有相同数字的每个内部列表,附加到listTwo只有位置3中具有最大值的内部列表

例如,inner list 0inner list 1 1中的position 09中的position 2都有inner list 09 } position 3中有一个inner list 16position 3有一个inner list 1,所以我想追加inner list 9而不是listTwoinner list 2。由于2position 012position 1for items in listOne : #for all items where items[0] and items[2] are equal : #tempList = [] #tempList.append(items) #tempList.sort(key = lambda x: (x[3])) #for value in tempList[0] : #listTwo.append(all lists with value in tempList[0]) 的唯一列表,因此无需将其与其他任何内容进行比较,并且可以追加to listTwo。

我想的是:

cv2.error: /home/desktop/OpenCV/opencv/modules/core/src/matrix.cpp:2294:
 error: (-215) d == 2 && (sizes[0] == 1 || sizes[1] == 1 || 
sizes[0]*sizes[1] == 0) in function create

但是我不知道如何在没有很多非常糟糕的代码的情况下实现这一点,对于#pythonic"排序这些清单的方法?

3 个答案:

答案 0 :(得分:1)

也许把所有东西扔进字典?像这样:

def strangeFilter(listOne):
    listTwo = []
    d = {}

    for innerList in listOne:
        positions = (innerList[0],innerList[2])
        if positions not in d:
            d[positions] = []
        d[positions].append(innerList)

    for positions in d:
        listTwo.append(max(d[positions], key= lambda x: x[3]))

    return listTwo

不确定有多少' pythonic'这是解决方案,但它使用python定义的结构,并且具有O(n)

的良好时间顺序

答案 1 :(得分:1)

如果你想编写简洁的python,你将尽可能使用list comprehensions。你的描述有点令人困惑,但有点像

list_two = [inner_list for inner_list in list_one if inner_list[0] == inner_list[2]]

将为您提供02索引匹配的所有内部列表。然后你可以搜索所有这些以找到具有最大3索引的那个,假设没有任何关系

list_three = [0,0,0,0]
for i in list_two:
    if i[3] > list_three[3]:
        list_three = i

答案 2 :(得分:1)

对项目零和两个内部列表上的列表进行排序。使用itertools.groupby提取每个组中位置 3处具有最大值的项目。

import operator, itertools

# a couple of useful callables for the key functions
zero_two = operator.itemgetter(0,2)
three = operator.itemgetter(3)

a = [[2,1,12,22],[1,1,9,9],[2,1,12,10],
     [1,4,9,6],[8,8,8,1],[2,1,12,12],
     [1,3,9,8],[2,1,12,15],[8,8,8,0]
     ]

a.sort(key = zero_two)
for key, group in itertools.groupby(a, zero_two):
    print(key, max(group, key = three))

'''
>>> 
(1, 9) [1, 1, 9, 9]
(2, 12) [2, 1, 12, 22]
(8, 8) [8, 8, 8, 1]
>>>
'''
result = [max(group, key = three) for key, group in itertools.groupby(a, zero_two)]

您还可以对零,二,三项进行排序。然后按项目零和二分组,并提取该组的最后一项。

zero_two_three = operator.itemgetter(0,2,3)
zero_two = operator.itemgetter(0,2)
last_item = operator.itemgetter(-1)
a.sort(key = zero_two_three)
for key, group in itertools.groupby(a, zero_two):
    print(key, last_item(list(group)))
相关问题