Nested Lists and List Comprehensions

和自甴很熟 提交于 2019-12-24 11:29:49

问题


I am fairly new to Python and I'm having trouble figuring out how to apply a list comprehension to part of a nested list (specifically at the index level).

For instance, 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 would I alter my list comprehension to only apply the operation to index 1 of each sublist? I have experimented quite a bit with no success.


回答1:


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:


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 wouldn't scale well if you had sublists of many elements. If this is the case for you, an alternative could be use 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 to implement any type of manipulation on the sublists, but if the operation is basic and only dependent from the index of the sublist, Dan's solution will perform faster.

HTH!




回答3:


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 am assuming that by 'index 1' you mean the first element.
If you actually mean the second item (which is index 1) you will use sublist[1] instead of sublist[0].



来源:https://stackoverflow.com/questions/8399386/nested-lists-and-list-comprehensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!