使用列表理解的嵌套 For 循环 [英] Nested For Loops Using List Comprehension
问题描述
如果我有两个字符串,'abc'
和 'def'
,我可以使用两个 for 循环获得它们的所有组合:
If I had two strings, 'abc'
and 'def'
, I could get all combinations of them using two for loops:
for j in s1:
for k in s2:
print(j, k)
但是,我希望能够使用列表理解来做到这一点.我尝试了很多方法,但从未设法得到它.有人知道怎么做吗?
However, I would like to be able to do this using list comprehension. I've tried many ways, but have never managed to get it. Does anyone know how to do this?
推荐答案
lst = [j + k for j in s1 for k in s2]
或
lst = [(j, k) for j in s1 for k in s2]
如果你想要元组.
就像问题中一样,for j...
是外循环,for k...
是内循环.
Like in the question, for j...
is the outer loop, for k...
is the inner loop.
本质上,您可以在列表推导式中根据需要拥有任意数量的独立for x in y"子句,只需一个接一个地粘贴即可.
Essentially, you can have as many independent 'for x in y' clauses as you want in a list comprehension just by sticking one after the other.
为了使其更具可读性,请使用多行:
To make it more readable, use multiple lines:
lst = [
j + k # result
for j in s1 # for loop
for k in s2 # for loop
# condition
]
这篇关于使用列表理解的嵌套 For 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!