HackerRank: List Comprehension 笔记和题解
HackerRank List Comprehension 题解以及 List Comprehension 的用法解释。题目:"Let's learn about list comprehensions! You are given three integers $x$, $y$ and $z$ representing the dimensions of a cuboid along with an integer. Print a list of all possible coordinates given by ..."
Table of Contents
题目
在做这一题之前,我一直都不知道这个技巧叫 list comprehension。偶尔有用到,但因为不熟,我总是只能用一层。做了这题终于是知道这个的语法了。
笔记
List Comprehension 用法
基础应用
最简单的应用,比如我们要创建一个二维的 list,由 [1,2,3]
和 [4,5,6]
pair组成。
基础的写法是:
result = []
for i in [1,2,3]:
for j in [4,5,6]:
temp = [i,j]
result.append(temp)
print(result)
#输出:[[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]]
但其实这个可以一行搞定:
result = [[x, y] for x in [1,2,3] for y in [4,5,6]]
print(result)
#输出:[[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]]
相信很多人和我一样,在 Stack Overflow 搜的时候,见过这样的写法,但可能一直不确定它的语法。
它的语法其实是这样的:
[ expression-involving-loop-variables for outer-loop-variable in outer-sequence for inner-loop-variable in inner-sequence ]
也就是先写带 variable 的 expression,再跟上连续的 for in。
加条件
还可以在这个基础上进一步做筛选:
[ expression-involving-loop-variable for loop-variable in sequence if boolean-expression-involving-loop-variable ]
也就是先写带 variable 的 expression,再跟上连续的 for in。
加上 x + y = 7
:
result = [[x, y] for x in [1,2,3] for y in [4,5,6] if x+y==7]
print(result)
#输出:[[1, 6], [2, 5], [3, 4]]
题解
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
l = [[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]
print(l)
然的博客 Newsletter
Join the newsletter to receive the latest updates in your inbox.