python列表解析实例

if起条件判断作用,满足条件的,返回最终生成的列表

1
[i for i in range(k) if condition]
1
2
3
4
5
[i for i in range(10) if i%2 == 0]

output:

[0, 2, 4, 6, 8]

if…else用来判断或赋值,满足条件的i以及j生成最终的列表

1
[i if condition else j for exp]
1
2
3
4
5
6
[i if i == 0 else 100 for i in range(10)]

output:

[0, 100, 100, 100, 100, 100, 100, 100, 100, 100]

应用在代码中:

1
2
3
4
5
state_dict = {
k: v
for k, v in state_dict.items()
if k in model_dict and v.shape == model_dict[k].shape
}

参考

https://blog.csdn.net/ZK_J1994/article/details/72809260

https://github.com/meder411/Tangent-Images/blob/master/experiments/semantic_segmentation/ss/models/build.py


python列表解析实例
http://yojayc.github.io/2021/10/28/python列表解析实例/
作者
Truman
发布于
2021年10月28日
更新于
2026年4月5日
许可协议