嵌套循环使用列表理解 [英] Nested For Loops Using List Comprehension

查看:84
本文介绍了嵌套循环使用列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个字符串,'abc''def',我可以得到它们的所有组合使用两个循环:

 对于s1中的j:
对于s2中的k:
print(j ,k)

然而,我希望能够使用列表理解来做到这一点。我已经尝试了很多方法,但从来没有设法得到它。有没有人知道如何做到这一点?

解决方案

  lst = [j + k for j在s1中为s2] 



< pre $ lst = [(j,k)for s in s1 for k in 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.

这篇关于嵌套循环使用列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆