[英]What is the equivalent of the following Python list comprehension in Fortran?
[英]What is the explanation of the following list comprehension?
input_shape = tuple([i for i in input_shape if i is not None])
我是python新手,不了解那里发生了什么。 如我所见,可能是C
的int a = 5 > 2 ? val1 : val2;
类似物int a = 5 > 2 ? val1 : val2;
int a = 5 > 2 ? val1 : val2;
,但我不知道。
我试图将其分成很小的部分以进行理解,但对我而言仍然没有意义。 像那样:
i // this is already wrong for being single
for i in input_shape //that's correct for cicle
if i is not None //ugh... so, and what if?
未通过测试的项目(此处为“无”)将被循环跳过。
input_shape = tuple([i for i in input_shape if i is not None])
# Roughly equivalent to
result = []
for i in input_shape:
if i is not None:
result.append(i)
input_shape = tuple(result)
在概念上相同,除了列表理解会更快,因为循环是由解释器内部完成的。 同样,显然不会留下result
变量。
i for i
可以是任何值, x for x
, y for y
,甚至Kosmos for Kosmos
。
>>> input_shape = [1, 2, 3]
>>> input_shape = tuple([i for i in input_shape if i is not None])
>>> input_shape
(1, 2, 3)
在这里您可以看到,它通过遍历每个项目将我的列表转换为元组。
研究一个叫做列表理解的东西,因为我很难解释它
input_shape = [1,2,3,None,5,1]
print(input_shape)
input_shape = tuple([i for i in input_shape if i is not None])
print(input_shape)
o / p
[1, 2, 3, None, 5, 1]
(1, 2, 3, 5, 1)
如@spectras所指出的,未通过测试的项目(此处为“无”)将被循环跳过。
以下是列表理解 :
[i for i in input_shape if i is not None]
它仅返回不为None
元素
然后,调用tuple()
将结果列表转换为元组。
通过使用如下所示的普通for
循环,可以实现相同的结果:
input_shape = [1, 2, None, 'a', 'b', None]
result = []
for i in input_shape:
if i is not None:
result.append(i)
print(result)
# Output: [1, 2, 'a', 'b']
现在,我们将result
(类型为list
)转换为tuple
如下所示:
final_result = tuple(result)
print(final_result)
# Output: (1, 2, 'a', 'b')
你几乎要分开了。 内部部分(如果)是您指出错误的表达式( i
),实际上它在内部。 它的作用是用方括号[]
; 它将这些东西放在列表中。 光谱的答案显示了如何使用变量保存该列表。 该构造称为列表理解 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.