解释python列表理解技术 [英] Explain python list comprehension technique

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

问题描述

有人可以请解释一下这段代码.

Can someone please explain this bit of code please.

>>> guest=['john','sue','chris']
>>> [(a,b,c) for a in guest for b in guest for c in guest]

有了这些结果...

[('john', 'john', 'john'), ('john', 'john', 'sue'), ('john', 'john', 'chris'), ('john', 'sue', 'john'), ('john', 'sue',
'sue'), ('john', 'sue', 'chris'), ('john', 'chris', 'john'), ('john', 'chris', 'sue'), ('john', 'chris', 'chris'), ('sue
', 'john', 'john'), ('sue', 'john', 'sue'), ('sue', 'john', 'chris'), ('sue', 'sue', 'john'), ('sue', 'sue', 'sue'), ('s
ue', 'sue', 'chris'), ('sue', 'chris', 'john'), ('sue', 'chris', 'sue'), ('sue', 'chris', 'chris'), ('chris', 'john', 'j
ohn'), ('chris', 'john', 'sue'), ('chris', 'john', 'chris'), ('chris', 'sue', 'john'), ('chris', 'sue', 'sue'), ('chris'
, 'sue', 'chris'), ('chris', 'chris', 'john'), ('chris', 'chris', 'sue'), ('chris', 'chris', 'chris')]

我知道(a,b,c)正在构造一个三值元组,但我不了解循环的情况.谢谢

I understand the (a,b,c) is constructing a three value tuple but I don't understand whats going on with the loops. Thanks

推荐答案

这是一个嵌套列表理解,您可以按照理解中出现的顺序扩展循环,以了解发生了什么:

It's a nested list comprehension, and you can expand the loops in the same order they appear in the comprehension to understand what's happening:

result = []
for a in guest:
    for b in guest:
        for c in guest:
            # yield (a,b,c)
            result.append((a,b,c))

这篇关于解释python列表理解技术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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