[英]Nested generator or iterator for python
I have the next list: 我有下一个列表:
texts = [['abcdD', 'asdfaD'], ['qerqD', 'asdfafdasD']]
I want to delete all character D
from the right part of all strings. 我想从所有字符串的右侧删除所有字符
D
For one list I can do it easily: 对于一个列表,我可以轻松做到:
res1 = [el.strip('D') for el in texts[0]] # ['abcd', 'asdfa']
Now I'm trying the same for each text: 现在,我为每个文本尝试相同的操作:
res2 = [el.strip('D') for text in texts for el in text]
But it returns ONE list (combine my two!): 但它返回一个列表(将我的两个列表合并!):
['abcd', 'asdfa', 'qerq', 'asdfafdas']
When I need next: 当我需要下一个时:
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
How to do it correct? 如何正确执行?
You can use this recursive approach for arbitrary deeply nested structures: 您可以将这种递归方法用于任意深度嵌套的结构:
def f(s):
return [q.strip('D') if isinstance(q, basestring) else f(q)
for q in s]
(Use str
instead of basestring
in Python3.) (使用
str
代替basestring
在Python3。)
Example: 例:
f([['abcdD', 'asdfaD'], ['qerqD', 'asdfafdasD']])
returns: 返回:
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
You can try this: 您可以尝试以下方法:
texts = [['abcdD', 'asdfaD'], ['qerqD', 'asdfafdasD']]
new_texts = [[b[:-1] if b.endswith('D') else b for b in i] for i in texts]
Output: 输出:
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
how about a ' map
happy' approach - just for fun, not any advantages I can see 如何使用“快乐
map
”方法-只是为了娱乐,我看不到任何优势
list(map(list, map(lambda txt: map(lambda x: x.rstrip('D'), txt), texts)))
Out[240]: [['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
As mentioned in my comment, you'll need to nest one of the loops. 如我的评论所述,您需要嵌套一个循环。
x = [['abcdD', 'asdfaD'], ['qerqD', 'asdfafdasD']]
y = [[j.rstrip('D') for j in i] for i in x]
y
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
Which is easy to understand if you convert the above to a nested loop - 如果将以上内容转换为嵌套循环,这很容易理解-
y = []
for i in x:
y.append([])
for j in i:
y[-1].append(j.rstrip('D'))
y
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
What you decide to use is really a matter of style. 您决定使用的实际上是样式问题。 The list comprehension is concise, but suffers from readability issues.
列表理解很简洁,但是存在可读性问题。 The loop is generally very fast and readable.
循环通常非常快速且可读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.