python - 双 for 循环列表理解

标签 python list list-comprehension

我正在尝试使用列表理解执行以下操作:

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

以下是在没有列表推导的情况下如何做到这一点:

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']]

关于python - 双 for 循环列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33249350/

相关文章:

python - iPython:无法安装笔记本。请安装 ipython-notebook

python - 两个单词列表的概率分布

python - 使用 python 遵循正态分布从列表中选择一个元素

python:如何制作全部小写的列表?

Python根据用户输入保存到特定目录

python - 带范围的字典理解

Python 用条件将两个列表相交

python - 是否可以在 Python 的一条语句中连接列表索引?

python - 具有列表理解的类变量的范围

python - 使用 pymongo 创建时区感知 ISODate