使用Python高阶函数处理列表

星辰

我已经列出了这个清单;每个项目都是一个包含逗号(在某些情况下)和冒号(总是)的字符串:

dinner = [
    'cake,peas,cheese : No',
    'duck,broccoli,onions : Maybe',
    'motor oil : Definitely Not',
    'pizza : Damn Right',
    'ice cream : Maybe',
    'bologna : No',
    'potatoes,bacon,carrots,water: Yes',
    'rats,hats : Definitely Not',
    'seltzer : Yes',
    'sleeping,whining,spitting : No Way',
    'marmalade : No'
]

我想从上面的列表中创建一个新列表,如下所示:

['cake : No',
 'peas : No',
 'cheese : No',
 'duck : Maybe',
 'broccoli : Maybe',
 'onions : Maybe',
 'motor oil : Definitely Not',
 'pizza : Damn Right',
 'ice cream : Maybe',
 'bologna : No',
 'potatoes : Yes',
 'bacon : Yes',
 'carrots : Yes',
 'water : Yes',
 'rats : Definitely Not',
 'hats : Definitely Not',
 'seltzer : Yes',
 'sleeping : No Way',
 'whining : No Way',
 'spitting : No Way',
 'marmalade : No']

但是我想知道是否/如何在一两个主要使用Python高阶函数的有效代码中做到这一点。我一直在尝试:

reduce(lambda x,y: x + y, (map(lambda x: x.split(':')[0].strip().split(','), dinner)))

...产生这个:

['cake',
 'peas',
 'cheese',
 'duck',
 'broccoli',
 'onions',
 'motor oil',
 'pizza',
 'ice cream',
 'bologna',
 'potatoes',
 'bacon',
 'carrots',
 'water',
 'rats',
 'hats',
 'seltzer',
 'sleeping',
 'whining',
 'spitting',
 'marmalade']

...但是我正在努力将冒号后的每个字符串片段附加到每个项目上。

冠军

假设您确实需要它作为字符串列表和字典列表,看起来像是更好的数据结构。

通过简化理解,您可以执行以下操作:

>>> [[x+':'+y for x in i.split(',')]
...  for i, y in map(lambda l: map(str.strip, l.split(':')), dinner)]
[['cake:No', 'peas:No', 'cheese:No'],
 ['duck:Maybe', 'broccoli:Maybe', 'onions:Maybe'],
 ['motor oil:Definitely Not'],
 ...
 ['marmalade:No']]

现在只需add列出:

>>> from operator import add
>>> reduce(add, ([x+':'+y for x in i.split(',')]
...              for i, y in map(lambda l: map(str.strip, l.split(':')), dinner)), [])
['cake:No',
 'peas:No',
 'cheese:No',
 'duck:Maybe',
 ...
 'marmalade:No']

或者只是将列表弄平:

>>> [a for i, y in map(lambda l: map(str.strip, l.split(':')), dinner) 
...  for a in (x+':'+y for x in i.split(','))]
['cake:No',
 'peas:No',
 'cheese:No',
 'duck:Maybe',
 ...
 'marmalade:No']

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章