我有以下代码我使用映射在Python嵌套列表,以产生具有相同结构的列表。

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

可以这样用单独列表解析完成(不使用映射函数)?

有帮助吗?

解决方案

有关的嵌套列表可使用嵌套列表解析:

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

我个人觉得map更清洁在这种情况下,即使我几乎总是喜欢列表理解。所以,这真的是你的电话,因为无论是将工作。

其他提示

记住的Python禅:

  

有一般不止一个 - 可能的若干的 - 明显的方式做到这一点**

**注:编辑精度

反正我喜欢地图。

from functools import partial
nested_list = map( partial(map, str.upper), nested_list )

地图肯定是做你想要的东西更清洁的方式。可以嵌套列表理解,虽然,也许这就是你以后是什么?

[[ix.upper() for ix in x] for x in nested_list]

下面是用于<强> 嵌套列表的解决方案,具有任意深度

def map_nlist(nlist=nlist,fun=lambda x: x*2):
    new_list=[]
    for i in range(len(nlist)):
        if isinstance(nlist[i],list):
            new_list += [map_nlist(nlist[i],fun)]
        else:
            new_list += [fun(nlist[i])]
    return new_list

要大写所有你列表元素,只需输入

In [26]: nested_list = [['Hello', 'World'], ['Goodbye', [['World']]]]
In [27]: map_nlist(nested_list,fun=str.upper)
Out[27]: [['HELLO', 'WORLD'], ['GOODBYE', [['WORLD']]]]

和更重要的是,这个递归函数可以做的比这更多!

我是新来的蟒蛇,随时洽谈!

其他海报已经给出了答案,但每当遇到麻烦包裹我的头的功能结构的时候,我吞下我的骄傲和拼出来有明确的非最优方法和/或对象速记。你说你想要与发电机结束了,所以:

for xs in n_l:
    def doUpper(l):
        for x in l:
            yield x.upper()
    yield doUpper(xs)

for xs in n_l:
    yield (x.upper() for x in xs)

((x.upper() for x in xs) for xs in n_l)

有时,清洁剂,以保持手写版本之一。对我来说,地图和减少有时使它更加明显,但是Python成语可能是其他人更明显。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top