python 的嵌套生成器或迭代器
Nested generator or iterator for python
我有下一个列表:
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]
但它 returns 一个列表(结合我的两个!):
['abcd', 'asdfa', 'qerq', 'asdfafdas']
下次我需要的时候:
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
如何做正确?
你可以试试这个:
texts = [['abcdD', 'asdfaD'], ['qerqD', 'asdfafdasD']]
new_texts = [[b[:-1] if b.endswith('D') else b for b in i] for i in texts]
输出:
[['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']])
returns:
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
如我评论中所述,您需要嵌套其中一个循环。
x = [['abcdD', 'asdfaD'], ['qerqD', 'asdfafdasD']]
y = [[j.rstrip('D') for j in i] for i in x]
y
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
如果将上面的转换为嵌套循环,这很容易理解 -
y = []
for i in x:
y.append([])
for j in i:
y[-1].append(j.rstrip('D'))
y
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
您决定使用什么实际上是风格问题。列表理解简洁,但存在可读性问题。循环通常非常快且可读。
“map
快乐”的方法怎么样 - 只是为了好玩,没有任何我能看到的优势
list(map(list, map(lambda txt: map(lambda x: x.rstrip('D'), txt), texts)))
Out[240]: [['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
我有下一个列表:
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]
但它 returns 一个列表(结合我的两个!):
['abcd', 'asdfa', 'qerq', 'asdfafdas']
下次我需要的时候:
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
如何做正确?
你可以试试这个:
texts = [['abcdD', 'asdfaD'], ['qerqD', 'asdfafdasD']]
new_texts = [[b[:-1] if b.endswith('D') else b for b in i] for i in texts]
输出:
[['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']])
returns:
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
如我评论中所述,您需要嵌套其中一个循环。
x = [['abcdD', 'asdfaD'], ['qerqD', 'asdfafdasD']]
y = [[j.rstrip('D') for j in i] for i in x]
y
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
如果将上面的转换为嵌套循环,这很容易理解 -
y = []
for i in x:
y.append([])
for j in i:
y[-1].append(j.rstrip('D'))
y
[['abcd', 'asdfa'], ['qerq', 'asdfafdas']]
您决定使用什么实际上是风格问题。列表理解简洁,但存在可读性问题。循环通常非常快且可读。
“map
快乐”的方法怎么样 - 只是为了好玩,没有任何我能看到的优势
list(map(list, map(lambda txt: map(lambda x: x.rstrip('D'), txt), texts)))
Out[240]: [['abcd', 'asdfa'], ['qerq', 'asdfafdas']]