简体   繁体   English

python代码有替代的有效方法吗?

[英]Is there an alternative efficient way for the python code?

Below is the one I tried.下面是我试过的。 I am looking for an easiest and efficient alternative way.我正在寻找一种最简单有效的替代方法。 Any help would be appreciated任何帮助,将不胜感激

y = [None] * 620
for i in range(0,204):
    y[i] = 3
for i in range(204,419):
    y[i] = 1
for i in range(419,620):
    y[i] = 2

y = [3] * 204 + [1] * (419 - 204) + [2] * (620 - 419)怎么样?

In general you can do something like this:一般来说,你可以这样做:

stops = [204, 419, 620]
nums = [3, 1, 2]

array = []
for i in range(total_length):
    if i < stops[0]:
        array.append(nums[0])
    elif i < stops[1]:
        array.append(nums[1])
    # more elifs go here
    else:
        array.append(nums[-1])

您可以使用列表理解

[ 3 if x >= 0 and x < 204 else 1 if x >= 204 and x < 419 else 2 for x in range(0, 620)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM