Python 3.4: adding value to list if condition exists
Solution 1
First of all:
myNewList = []
myNewList.append([[a,b] for a,b in mainList if a in secondaryList])
simply is the same as
myNewList = [[a,b] for a,b in mainList if a in secondaryList]
Then:
What you're building is functionally a python dictionary. Your two-element lists in mainList
are the same as dict.items()
!
So what you'd do is build a dict
out of mainList
(reversing it, because usually, you'd just save the last, not the first occurence):
mainDict = dict([reversed(mainList)])
Then you just make your new list:
myNewList = [ (key, mainDict[key]) for key in secondaryList ]
Solution 2
You can use a set to store the first elements and then check for existing the first element before adding the sub-lists :
>>> seen=set()
>>> l=[]
>>> for i,j in mainList:
... if i in secondaryList and i not in seen:
... seen.add(i)
... l.append([i,j])
...
>>> l
[[9, 5], [23, 1]]
Or you can use collections.defaultdict
and deque
with specifying its maxlen
.But note that you need to loop over your list from end to start if you want the first occourance of a
because deque
will keep the last insert value :
>>> from collections import defaultdict
>>> from functools import partial
>>> d=defaultdict(partial(deque, maxlen=1))
>>> for i,j in mainList[::-1]:
... if i in secondaryList:
... d[i].append(j)
...
>>> d
defaultdict(<functools.partial object at 0x7ff672706e68>, {9: deque([5], maxlen=1), 23: deque([1], maxlen=1)})
jul
Updated on June 04, 2022Comments
-
jul almost 2 years
i have a scenario like this one:
mainList = [[9,5],[17,3],[23,1],[9,2]] secondaryList = [9,12,28,23,1,6,95] myNewList = [] myNewList.append([[a,b] for a,b in mainList if a in secondaryList])
this, return me to me:
myNewList = [[9,5],[23,1],[9,2]]
but I need only the first occourance of "a". In other words I need to obtain:
myNewList = [[9,5],[23,1]]
How can I achieve this?
-
jul about 9 yearsDoes not work for me: mainDict = dict([reversed(secondaryList)]) ValueError: dictionary update sequence element #0 has length 7; 2 is required