python for循环仅执行一次? [英] python for-loop only executes once?

查看:2040
本文介绍了python for循环仅执行一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import numpy as np
def Vin(t):
    inputs = []
    for i in range (1000):
        if (-1)**(np.floor( 2 * t[i] )) == 1:
            Vin = (1)
            inputs.append(Vin)
        else:
            Vin = (-1)
            inputs.append(Vin)

        return inputs

当我在一系列t值上使用此功能时,我只会得到一个结果,

when I use this function on a range of t values, I only get one result,

input1=Vin(tpoints)
print (input1)

仅给出[1],而我希望函数为每个t值执行.

only gives [1], whereas I want the function to do it for every t value.

推荐答案

您将从for循环中的with返回,因此您将在循环的第一次迭代中从该函数返回.

You are returning from with in the for loop,So you would return from the function on first iteration of the loop.

您可以按以下方式重新编写功能

you may re-writ e the function as following

代码

def Vin(t):
    inputs = []
    for i in range (1000):
        if (-1)**(np.floor( 2 * t[i] )) == 1:
            inputs.append(1)
        else:
            inputs.append(-1)
    return inputs

在此处检查返回输入的缩进.

顺便说一句,您的函数可以简化为更多的Python语言和更有效的代码

BTW, your function can be reduced to as more pythonic and efficient code

def Vin(t):
 reduce map(lambda x:int((-1)**(np.floor( t[i] < 1))), range (1000))

这篇关于python for循环仅执行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆