打印([[i+j代表“abc”中的i]“def”中的j)

2024-03-29 09:47:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手。在

我不明白其中一个道理

print([[i+j for i in "abc"] for j in "def"])

你能帮我把理解转换成for循环吗?在

我无法通过for循环获得所需的结果:

^{pr2}$

以上是我对for循环的尝试。我遗漏了一些东西。下面应该是我想要的for循环中的期望结果。在

([[‘ad’, ‘bd’, ‘cd’], [‘ae’, ‘be’, ‘ce’], [‘af’, ‘bf’, ‘cf’]])

我相信这是一个婚姻。在

提前谢谢。在


Tags: infordefcdbebdadce
3条回答

对于这个理解的循环应该是这样的

result = []
for j in "def":
    r = []
    for i in "abc":
        r.append(i+j)
    result.append(r)
a = 'abc'
b = 'def'

>>> [[x+y for x in a]for y in b]
[['ad', 'bd', 'cd'], ['ae', 'be', 'ce'], ['af', 'bf', 'cf']]

循环

^{pr2}$

要解开这样的理解,最简单的方法就是一次只理解一个,然后把这个理解写成一个循环。所以:

[[i+j for i in "abc"] for j in "def"]

变成:

^{pr2}$

好吧,酷。现在我们已经摆脱了外在的理解,这样我们就可以下一步解开内在的理解:

outer_list = []
for j in "def":
    inner_list = []
    for i in "abc":
        inner_list.append(i + j)
    outer_list.append(inner_list)

相关问题 更多 >