在Python中使用List Comprehension映射嵌套列表? [英] Mapping a nested list with List Comprehension in Python?

查看:74
本文介绍了在Python中使用List Comprehension映射嵌套列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,可用于在Python中映射嵌套列表以生成具有相同结构的列表.

I have the following code which I use to map a nested list in Python to produce a list with the same structure.

>>> nested_list = [['Hello', 'World'], ['Goodbye', 'World']]
>>> [map(str.upper, x) for x in nested_list]
[['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']]

这可以单独使用列表理解来完成(不使用map函数)吗?

Can this be done with list comprehension alone (without using the map function)?

推荐答案

对于嵌套列表,您可以使用嵌套列表理解:

For nested lists you can use nested list comprehensions:

nested_list = [[s.upper() for s in xs] for xs in nested_list]

我个人认为map在这种情况下会更干净,尽管我几乎总是更喜欢列表理解.所以这真的是您的电话,因为任何一个都可以.

Personally I find map to be cleaner in this situation, even though I almost always prefer list comprehensions. So it's really your call, since either will work.

这篇关于在Python中使用List Comprehension映射嵌套列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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