Python迭代列表列表

问题描述 投票:0回答:4

我有列表列表,我需要通过Python遍历每个字符串,删除空格(strip)并将列表保存到新列表中。

例如。原始清单:org = [['a','b'],['c','d'],['e','f']]

期待新的清单:new = [['a','b'],['c','d'],['e','f']]

我从下面的代码开始,但不知道如何将已剥离的对象添加到新的列表列表中。 new.append(item) - 创建没有内部列表的简单列表。

new = [] for items in org: for item in items: item= item.strip() new.append(item)

python python-3.x
4个回答
1
投票

就像是 -

new = []
for items in org:
  new.append([])
  for item in items:
    item= item.strip()
    new[-1].append(item)

2
投票

您可以使用嵌套列表推导来删除每个子列表中的每个单词:

new = [[s.strip() for s in l] for l in org]

1
投票

此解决方案适用于任何列表深度:

orig = [[' a', 'b '], ['c ', 'd '], ['e ', ' f']]

def worker(alist):

    for entry in alist:
        if isinstance(entry, list):
            yield list(worker(entry))
        else:
            yield entry.strip()

newlist = list(worker(orig))

print(orig)
print(newlist)

0
投票

试试这个:

org = [ [' a ','b '],['c ',' d '],['e ',' f'] ]
new = []
temp = []

for o in org:
    for letter in o:
        temp.append(letter.strip())
    new.append(temp)
    temp = []

结果:

[['a', 'b'], ['c', 'd'], ['e', 'f']]

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.