Python列表理解,一次添加更多元素(Python list comprehension with adding more elements in one go)

编程入门 行业动态 更新时间:2024-10-21 03:42:23
Python列表理解,一次添加更多元素(Python list comprehension with adding more elements in one go)

如果您在一个步骤中创建目标列表的多个元素,我试图弄清楚是否可以进行列表理解。

让我们有一个这样的列表: input_list=['A','B','C/D','E']我最想得到的是output_list=['A','B','C','D','E'] 。

这是我现在拥有的一段代码:

output=[] for x in input: if '/' in x: output+=x.split('/') else: output.append(x)

我想出的唯一列表理解是: [x.split('/') if '/' in x else x for x in input]但显然,它不是我需要的,因为它输出这个嵌套列表: ['A','B',['C','D'],'E']

有可能,或者我只是想从一个简单的列表理解中得到太多的东西?

I am trying to figure out if it is possible to make a list comprehension if you create more than one element of the target list in one step.

Lets have a list like this: input_list=['A','B','C/D','E'] and what I want to get in the end is output_list=['A','B','C','D','E'].

This is the piece of code I have now:

output=[] for x in input: if '/' in x: output+=x.split('/') else: output.append(x)

The only list comprehension that I came up with was: [x.split('/') if '/' in x else x for x in input] but obviously, it is not what I need as it outputs this nested list: ['A','B',['C','D'],'E']

Is it possible, or I just want too much from a simple list comprehension?

最满意答案

使用嵌套列表理解:

>>> input_list = ['A','B','C/D','E'] >>> [y for x in input_list for y in (x.split('/') if '/' in x else [x])] ['A', 'B', 'C', 'D', 'E']

或者使用itertools.chain.from_iterable :

>>> from itertools import chain >>> list(chain.from_iterable(x.split('/') if '/' in x else [x] for x in input_list)) ['A', 'B', 'C', 'D', 'E']

请注意,我们需要在没有/字符串周围添加[] ,因为字符串也是可迭代的。

Use a nested list-comprehension:

>>> input_list = ['A','B','C/D','E'] >>> [y for x in input_list for y in (x.split('/') if '/' in x else [x])] ['A', 'B', 'C', 'D', 'E']

Or using itertools.chain.from_iterable:

>>> from itertools import chain >>> list(chain.from_iterable(x.split('/') if '/' in x else [x] for x in input_list)) ['A', 'B', 'C', 'D', 'E']

Note that we need to add [] around a string without / because strings are iterable too.

更多推荐

本文发布于:2023-08-06 14:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1450256.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   更多   列表   Python   elements

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!