Pra*_*ant 3 python list-comprehension
什么是简单的列表理解(不使用任何新模块或字典)以获得如下输出:
[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
Run Code Online (Sandbox Code Playgroud)
这里0每个 s 之间的1s 数量从 0 增加到 10 倍。
在不使用列表理解的情况下,我使用简单的 for 循环得到了输出:
for i in range(12):
if i==0:
print(1, end=", ")
else:
for j in range(i):
if i==j+1:
print(1, end=", ")
else:
print(0, end=", ")
Run Code Online (Sandbox Code Playgroud)
只是想看看如何将这些循环转换为列表理解
您可以使用以下列表推导式生成1后面跟越来越多的0' 的列表:
[[1] + [0] * i for i in range(n)]
Run Code Online (Sandbox Code Playgroud)
对于n = 4,这将产生:
[[1], [1, 0], [1, 0, 0], [1, 0, 0, 0]]
Run Code Online (Sandbox Code Playgroud)
您可以通过将其嵌套在另一个理解中来展平该列表,然后添加尾随1:
res = [i for sub in [[1] + [0] * i for i in range(n)] for i in sub] + [1]
Run Code Online (Sandbox Code Playgroud)
Again, for n = 4 this produces:
[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1]
Run Code Online (Sandbox Code Playgroud)
If you can use libraries, you can use itertools.chain.from_iterable to flatten the list:
res = list(itertools.chain.from_iterable([1] + [0] * i for i in range(n))) + [1]
Run Code Online (Sandbox Code Playgroud)
The output will be the same.
As pointed out by @KellyBundy in the comments, the need for the trailing 1 can be removed by changing the innermost comprehension in the above code to
[0] * i + [1] for i in range(-1, n)
Run Code Online (Sandbox Code Playgroud)
This makes use of the fact that [0] * n = [] for n <= 0. For n = 4 this directly produces
[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |