更新时间:2022-11-22 11:27:48
lst = [j + k for j在s1中为s2]
或
$ b $ p
$ b $ p $ j
$ p $ j code $ c $是外部循环,为k ...
是内部循环。
基本上,独立于'y'条款中的x,就像你想通过一个接一个地粘贴列表所理解的一样。
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]
or
lst = [(j, k) for j in s1 for k in s2]
if you want tuples.
Like in the question, for j...
is the outer loop, for k...
is the inner loop.
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.