嵌套列表和列表理解 [英] Nested Lists and List Comprehensions

查看:47
本文介绍了嵌套列表和列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python还是很陌生,我在弄清楚如何将列表理解应用于嵌套列表的一部分(特别是在索引级别)时遇到了麻烦.

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]

我将如何更改列表理解以仅将操作应用于每个子列表的索引1?我已经尝试了很多,但没有成功.

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.

推荐答案

mac's 的更通用的版本:

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

这篇关于嵌套列表和列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆