python - How to optimize code for deleting n position in all the lists from a list of lists -


i search site issue , found many posts deleting specific values list of lists.

however, doesn't answer question.

lets have:

mylist=[[1,2,3,4],[100,374,283,738]] 

now, in mind 2 lists linked. list 1 number items: 1, 2, 3, 4,... , list 2 feature of these items (for example prices: $100, $374, etc).

now, want delete list elements (number , price) if list2 hihger of value (for example if item expensive, more $300)

i have been trying , got this:

n=0 # counter position in list in mylist[1]:     if i>300:         j in mylist:             del j[n]     n=n+1 

result:

[[1,3],[100,283]] 

this works. looks not efficient: have access list several times , have create new variables. many loops.

since lists can use comprehension lists wonder if there more efficient , elegant method getting same result

thanks

use zip filtering generator expression:

>>> mylist = [[1,2,3,4], [100,374,283,738]] >>> mylist[:] = list(map(list, zip(*((a,b) a,b in zip(*mylist) if b<300)))) >>> mylist [[1, 3], [100, 283]] 

note keeps old mylist pointer, mimic way code modifies original list.


Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -