Skip to main content
 首页 » 编程设计

python之python 的嵌套生成器或迭代器

2025年05月04日21kerrycode

我有下一个列表:

texts = [['abcdD', 'asdfaD'], ['qerqD', 'asdfafdasD']] 

我想从所有字符串的右侧删除所有字符 D。

对于一个列表,我可以轻松做到:

res1 = [el.strip('D') for el in texts[0]] # ['abcd', 'asdfa'] 

现在我对每个文本都尝试相同的方法:

res2 = [el.strip('D') for text in texts for el in text] 

但它返回一个列表(结合我的两个!):

['abcd', 'asdfa', 'qerq', 'asdfafdas'] 

当我下一步需要时:

[['abcd', 'asdfa'], ['qerq', 'asdfafdas']] 

如何正确?

请您参考如下方法:

您可以对任意深度嵌套结构使用这种递归方法:

def f(s): 
  return [q.strip('D') if isinstance(q, basestring) else f(q) 
          for q in s] 

(在 Python3 中使用 str 而不是 basestring。)

例子:

f([['abcdD', 'asdfaD'], ['qerqD', 'asdfafdasD']]) 

返回:

[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]