提问人:kjfletch 提问时间:8/20/2009 最后编辑:Martijn Pieterskjfletch 更新时间:9/1/2016 访问量:18115
在 Python 中使用列表推导映射嵌套列表?[复制]
Mapping a nested list with List Comprehension in Python? [duplicate]
问:
我有以下代码,我用它来映射 Python 中的嵌套列表以生成具有相同结构的列表。
>>> nested_list = [['Hello', 'World'], ['Goodbye', 'World']]
>>> [map(str.upper, x) for x in nested_list]
[['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']]
这可以仅通过列表理解来完成吗(不使用地图函数)?
答:
16赞
Eli Courtwright
8/20/2009
#1
对于嵌套列表,可以使用嵌套列表推导式:
nested_list = [[s.upper() for s in xs] for xs in nested_list]
就我个人而言,我发现在这种情况下更干净,尽管我几乎总是更喜欢列表理解。所以这真的是你的决定,因为任何一个都可以。map
评论
0赞
SilentGhost
8/20/2009
在 py3k 中,map 需要对其应用一个列表。
4赞
KayEss
8/20/2009
#2
地图当然是一种更干净的方式,可以做你想做的事。不过,您可以嵌套列表理解,也许这就是您所追求的?
[[ix.upper() for ix in x] for x in nested_list]
评论
0赞
kjfletch
8/20/2009
是的,使用地图可能更干净,但我想使用生成器。
2赞
Karl Anderson
8/21/2009
#3
其他海报已经给出了答案,但每当我在脑海中遇到困难时,我都会吞下我的骄傲,并用明确的非最佳方法和/或对象来拼出它。你说你想最终得到一个发电机,所以:
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 习语对其他人来说可能更明显。
评论
0赞
Peter Suwara
2/19/2023
这是一个非常好的方法。如果您仍然不清楚某些东西是如何工作的,添加单元测试也很好。TDD 是逐步执行逻辑的好方法。当我们讨论 python 的禅宗主题时,“可读性很重要”。
6赞
Stuart Berg
3/15/2013
#4
记住 Python 的禅宗:
通常有不止一种 - 可能几种 - 明显的方法可以做到这一点。
** 注意:为准确起见,经过编辑。
无论如何,我更喜欢地图。
from functools import partial
nested_list = map( partial(map, str.upper), nested_list )
评论
0赞
Peter Suwara
2/19/2023
你的意思是:“应该有一种——最好只有一种——明显的方法可以做到这一点”?:)
2赞
Oldyoung
10/1/2014
#5
以下是具有任意深度的嵌套列表的解决方案:
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']]]]
更重要的是,这个递归函数可以做的不止这些!
我是python的新手,请随时讨论!
评论
0赞
0 _
6/18/2015
使用 代替 ,以避免为每个项目重新创建新列表。append
+=
0赞
Oldyoung
1/21/2016
@IoannisFilippidis Filippidis 嘿,感谢您的回复,但您能给我有关 += 问题的更多详细信息吗?我不太明白其中的区别......(好久不用python..)
1赞
0 _
1/25/2016
让。使用相同的实例扩展为另一个元素。相反,创建一个新列表,然后从内存中消除该列表。更正我之前的评论:我以为它像 一样工作,但使用表明它没有。更多细节可以在这里找到。a = list()
a.append(0)
list
a += [0]
[0]
__iadd__
__add__
id
0赞
MaxU - stand with Ukraine
12/28/2016
这真的很聪明!
评论