如何编写给定代码的列表理解? [英] How do i write the list comprehension for the given code?
本文介绍了如何编写给定代码的列表理解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是python的新手.
I am fairly new to python.
l = []
for i in range(x+1):
for j in range(y+1):
for k in range(z+1):
if i+k+j!=n:
l.append([i,j,k])
我尝试过:
l = [[[i for i in range(x+1)] for j in range(y+1)] for k in range(z+1) if i+j+k != n]
但是它不起作用.
推荐答案
嵌套列表的理解可能有些棘手.您需要将三个元组追加到列表中.所以这意味着理解的第一部分应该是(i,j,k)
Nested list comprehensions can be a bit tricky. You need a three tuple to be appended to your list. So that means the first part of the comprehension should be (i,j,k)
[ (i,j,k) for i in range(x+1) for j in range(y+1) for k in range(z+1) if i+j+k != n]
然后,您需要将该追加添加到列表中,以i + j + k不等于n为条件.到if条件结束时.两者之间不应有任何其他[
或]
.
Then you need that append to be list to be conditional upon i+j+k not being equal to n. To the if condition comes at the end. There shouldn't be any other [
or ]
in between.
这篇关于如何编写给定代码的列表理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文