Python Break但返回或存储当前值

时间:2019-01-30 05:39:35

标签: python numpy for-loop break

如何实现带有中断的for循环,该循环还会在中断处返回值?

x = np.empty(1)

x[0] = 0.4

f = np.array([3,2,1,0,1,2,3])
y = np.empty(0)

for i in range(len(f)):
    if f[i+1] < f[i]:
        newx = x[i]*2
        y = np.append(y,f[i+1])
        x = np.append(x,newx)
    else:
        break

这将返回y = [2,1,0]和x = [0.4,0.8,1.6,3.2],但我希望它也返回值y = 1和x = 6.4,这将是下一次迭代。 / p>

3 个答案:

答案 0 :(得分:1)

尝试像这样向您的else块添加代码:

for i in range(len(f)):
    if f[i+1] < f[i]:
        newx = x[i]*2
        y = np.append(y,f[i+1])
        x = np.append(x,newx)
    else:
        y = np.append(y,f[i+1])
        x = np.append(x,newx)
        break

这可以锻炼。

答案 1 :(得分:0)

尝试这样的事情:

for i in range(len(f) - 1):        
    newx = x[i]*2
    y = np.append(y,f[i+1])
    x = np.append(x,newx)

    if f[i+1] > f[i]:
        break

此代码段还将在退出循环之前添加下一个迭代。

答案 2 :(得分:0)

只需添加一个新条件即可。

<?php

$adresses = array();
$sql = "select * from user_table ORDER BY date_registered DESC LIMIT 10";
if(mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)){
        array_push($adresses, $row["email"]);
        echo "<tr>";
        echo "<td>";
        echo $row["firstname"];
        echo "</td>";
        echo "<td>";
        echo $row["lastname"];
        echo "</td>";
        echo "<td>";
        echo $row["idnumber"];
        echo "</td>";
        echo "<td>";
        echo $row["qualification"];
        echo "</td>";
        echo "<td>";
        echo $row["dofa"];
        echo "</td>";
        echo "<td>";
        echo $row["date_registered"];
        echo "</td>";
        echo "<td>";
        echo '<button name="approve" value='. $row["user_id"].'>Approve</button> <button name="reject" value='. $row["user_id"].'>Reject</button>';
        echo "</td>";
        echo '</tr>';
    }
    if(isset($_POST['approve'])){
        mail($adresses[$_POST["approve"]],'subect 1','approved','From:email@example.com'); 
        //update DB to approved
    }elseif(isset($_POST['reject'])){
        //update DB to rejected
    }

}

print_r($adresses);

?>