Nested Lists and Lists

I'm new to Python, and it's hard for me to figure out how to apply list comprehension to part of a nested list (especially at the index level).

For example, if I have the following:

my_list = [[1,2], [3,7], [6,9], [4,3]] new_list = [[i*2 for i in sublist] for sublist in my_list] 

How can I change my understanding of the list to apply the operation only to index 1 of each sublist? I experimented quite a lot without success.

+1
source share
3 answers

A more general version of mac's :

 >>> my_list = [[1,2], [3,7], [6,9], [4,3]] >>> new_list = [[v*2 if i==0 else v for i,v in enumerate(sublist)] for sublist in my_list] >>> new_list [[2, 2], [6, 7], [12, 9], [8, 3]] 
+2
source

Are you looking for this?

 >>> my_list = [[1,2], [3,7], [6,9], [4,3]] >>> [[sublist[0] * 2, sublist[1]] for sublist in my_list] [[2, 2], [6, 7], [12, 9], [8, 3]] 

EDIT: The above solution will not scale well if you have sublists of many items. If this is the case for you, an alternative might be to use a mapping:

 >>> my_list = [[1,2], [3,7], [6,9], [4,3]] >>> def double_first(list_): ... list_[0] *= 2 ... return list_ ... >>> map(double_first, my_list) [[2, 2], [6, 7], [12, 9], [8, 3]] 

EDIT2: The solution in my first edit allows you to implement any type of manipulation in the sublists, but if the operation is basic and depends only on the subscription index, the Dan Solution will work faster.

NTN!

+1
source

you mean something like this:

 my_list = [[1,2], [3,7], [6,9], [4,3]] new_list = [sublist[0]*2 for sublist in my_list] Output: new_list == [2, 6, 12, 8] 

also you forgot to put commas between your sublists (fixed in my answer)

I assume that by index 1 you mean the first element.
If you really mean the second element (which is index 1), you will use sublist[1] instead of sublist[0] .

0
source

Source: https://habr.com/ru/post/1259702/


All Articles