一个更具Python性的单行线解决方案?

2024-04-26 02:27:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一个更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的单行程序,但没有声明那么多变量,但收效甚微。有人能帮忙吗?你知道吗


Tags: inapple列表foritemlistpearcream
0条回答
网友
1楼 · 发布于 2024-04-26 02:27:56

我想这个可以解决问题

x = [['apple strudel', 'apple, orange, pear ice cream'], ["test", "test1, test2, test3"]]

def flatten(x):
    return sum([(x.split(", ")) for x in sum(x, [])], [])

print(flatten(x))
网友
2楼 · 发布于 2024-04-26 02:27:56

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

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(", ")]

相关问题 更多 >

    热门问题