如何写为列表理解?

问题描述 投票:-1回答:2

我不太习惯使用python,因此我被要求将此代码编写为列表理解。

t_averaged = []
for i in range(len(i_averaged)-1):
    t_av = t[i_averaged [i] ]+ time_intervall /2
    t_averaged.append(t_av )
python for-loop append list-comprehension
2个回答
0
投票

这将是您的for循环,作为列表理解,假设在循环之前已引用i_averaged和time_interval。

 t_averaged = [t[i_averaged[i]] + time_interval/2 for i in range(len(i_averaged)-1)]

0
投票
squares = []
for x in range(10):
  squares.append(x ** 2)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]   

使用列表理解:

squares = [x ** 2 for x in range(10)]
    # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

尝试一下

© www.soinside.com 2019 - 2024. All rights reserved.