如果您在一个步骤中创建目标列表的多个元素,我试图弄清楚是否可以进行列表理解。
让我们有一个这样的列表: 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.
更多推荐
发布评论