更Pythonic的单线解决方案?

时间:2018-11-11 09:46:16

标签: python list

我正在寻找一种更Python化的单线来拆分和展平列表。原始列表如下所示:

negative_list = [['apple strudel', 'apple, orange, pear ice cream']]

使用上面的未处理列表,我需要将其转换为以下已处理列表:

negative_list = ['apple strudel', 'apple', 'orange', 'pear ice cream']

您会注意到,“苹果”,“橙色”,“梨冰淇淋”已在转换后的列表中拆分为单个项目。

我写了以下内容:

negative_list = []
negatives = []
negative_list = [['apple strudel', 'apple, orange, pear ice cream']]
negative_list = [item for sublist in negative_list for item in sublist]
for i in negative_list: 
    if ',' not in i: negatives.append(i.strip())
    else:
        for element in i.split(','): negatives.append(element.strip())
print(negative_list)
print(negatives)

我尝试编写Pythonic单行代码,但未声明太多变量,但收效甚微。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

在生成器表达式中使用itertools.chain.from_iterable

from itertools import chain

negative_list = [['apple strudel', 'apple, orange, pear ice cream']]

print(list(chain.from_iterable(x.split(', ') for x in negative_list[0])))
# ['apple strudel', 'apple', 'orange', 'pear ice cream']

答案 1 :(得分:-1)

您可以尝试此解决方案,尽管不建议将其用于生产代码:

negative_list = [['apple strudel', 'apple, orange, pear ice cream']]

negative_list = sum([elem.split(", ") for elem in negative_list[0]],[])
print(negative_list)

输出:

['apple strudel', 'apple', 'orange', 'pear ice cream']

另一种方法是对for使用嵌套的list-comprehension循环:

negative_list = [elem.strip() for item in negative_list[0] for elem in item.split(", ")]

答案 2 :(得分:-1)

我认为这可以解决问题

import re
p = re.compile('|'.join(map(re.escape, keywords)))
matched_list = [string for string in lst if p.search(string)]
相关问题