Double for循环列表理解 [英] Double for loop list comprehension

查看:87
本文介绍了Double for循环列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用列表推导进行以下操作:

I am trying to do following operation using list comprehensions:

Input: [['hello ', 'world '],['foo ',' bar']]
Output: [['hello', 'world'], ['foo', 'bar']]

在没有列表理解的情况下,这是可以做到的:

Here is how one can do it without list comprehensions:

a = [['hello ', 'world '],['foo ',' bar']]
b = []

for i in a:
   temp = []
   for j in i:
      temp.append( j.strip() )
      b.append( temp )

print(b)
#[['hello', 'world'], ['foo', 'bar']]

如何使用列表推导?

推荐答案

a = [['hello ', 'world '],['foo ',' bar']]
b = [[s.strip() for s in l] for l in a]
print(b)
# [['hello', 'world'], ['foo', 'bar']]

这篇关于Double for循环列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆