簡體   English   中英

如何從另一個列表列表中的條件項生成列表列表

[英]how to generate list of lists from conditional items in another list of lists

我有一個列表列表,並且正在嘗試從列表的第一個列表中的特定項目制作另一個列表列表

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

對於在位置02具有相同數字的每個內部列表,追加到listTwo僅在位置3具有最大值的內部列表

例如, inner list 0inner list 1都具有1position 09position 2 ,但inner list 0具有9position 3inner list 1具有6position 3 ,所以我要追加inner list 1 ,而不是inner list 9listTwo 由於inner list 2是唯一的列表,其position 02position 0 position 112 ,因此無需與其他任何內容進行比較,可以將其附加到listTwo。

我在想類似的東西:

for 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])

但是我不確定如何在沒有很多看起來很糟糕的代碼的情況下實現這一點,是否有建議使用“ pythonic”方式對這些列表進行排序?

也許把所有東西都丟進字典了嗎? 像這樣:

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)

如果您要編寫簡潔的python,則將盡可能使用列表推導。 您的描述有點混亂,但類似

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

對項目零和兩個內部列表中的列表進行排序。 使用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)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM