代码之家  ›  专栏  ›  技术社区  ›  kjfletch

用python中的列表理解来映射嵌套列表?

  •  9
  • kjfletch  · 技术社区  · 17 年前

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

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

    单靠列表理解(不使用map函数)就可以做到这一点吗?

    5 回复  |  直到 10 年前
        1
  •  13
  •   Eli Courtwright    17 年前

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

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

    我个人发现 map 在这种情况下更清楚一点,尽管我几乎总是喜欢列表理解。所以这真的是你的电话,因为两者都可以工作。

        2
  •  3
  •   KayEss    17 年前

    地图无疑是一种更清洁的方式来做你想做的事情。不过,你可以把清单的理解嵌套起来,也许这就是你想要的?

    [[ix.upper() for ix in x] for x in nested_list]
    
        3
  •  3
  •   Stuart Berg    13 年前

    记住巨蟒的禅:

    通常不止一个——而且可能 几个 --很明显的方法。*

    **注:为准确编辑。

    不管怎样,我更喜欢地图。

    from functools import partial
    nested_list = map( partial(map, str.upper), nested_list )
    
        4
  •  2
  •   Oldyoung    11 年前

    这是解决方案 具有任意深度的嵌套列表 :

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

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

    我是新来的巨蟒,请随意讨论!

        5
  •  0
  •   Karl Anderson    17 年前

    其他的海报也给出了答案,但是每当我在一个功能性的结构上绕着脑袋有困难的时候,我会吞下我的骄傲,并用明确的非最佳方法和/或对象将它拼出来。你说你最终想要一台发电机,所以:

    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)
    

    有时保存一个长手版本会更干净。对我来说,map和reduce有时会使它更明显,但对于其他人来说,python习惯用法可能更明显。

    推荐文章