我正在寻找一个更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的单行程序,但没有声明那么多变量,但收效甚微。有人能帮忙吗?你知道吗
我想这个可以解决问题
您可以尝试此解决方案,但不建议将其用于生产代码:
输出:
另一种方法是使用嵌套的
for
循环和list-comprehension
:相关问题 更多 >
编程相关推荐