[英]Python Iterating through list of lists
i have list of lists, i need via Python iterate through each string ,remove spaces (strip) and save list into new list. 我有列表列表,我需要通过Python遍历每个字符串,删除空格(带)并将列表保存到新列表中。
Eg original list: org = [ [' a ','b '],['c ',' d '],['e ',' f'] ] 例如原始列表:org = [[''','b'],['c','d'],['e','f']]
Expecting new list: new = [ ['a','b'],['c','d'],['e','f'] ] 期待新的列表:new = [[['a','b'],['c','d'],['e','f']]
I started with below code, but no idea how to add stripped objects into new list of lists. 我从下面的代码开始,但是不知道如何将剥离的对象添加到新的列表列表中。 new.append(item) - create simple list without inner list.
new.append(item)-创建没有内部列表的简单列表。
new = [] for items in org: for item in items: item= item.strip() new.append(item)
您可以使用嵌套列表推导来剥离每个子列表中的每个单词:
new = [[s.strip() for s in l] for l in org]
Something like - 就像是 -
new = []
for items in org:
new.append([])
for item in items:
item= item.strip()
new[-1].append(item)
This solution works for any list depth: 此解决方案适用于任何列表深度:
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)
Try this: 尝试这个:
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 = []
Result: 结果:
[['a', 'b'], ['c', 'd'], ['e', 'f']]
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.