【问题标题】:Is this possible Else condition to work after break & trying to change for loop value?在中断和尝试更改循环值之后,这可能是其他条件吗?
【发布时间】:2020-03-29 17:12:07
【问题描述】:

创建 150 的随机数并取 78 的统一样本

import numpy as np

population_data=np.random.randint(1,600,150) # 150 random numbers(integers) genereated 

sample_data=[]
sample_lenth=78

p=30/len(population_data)


for i in range(1,len(population_data)):

    if np.random.random() <=p:
        sample_data.append(population_data[i])
        print(i,len(sample_data))
        if sample_lenth==len(sample_data):
            break;
else: 
    i=10 # (basically wants to change the i value lower that for loop keep running )
    print(i)
        
           
    
print(len(sample_data))
print(sample_data)

for 循环仍在运行 150,这是有效的,我无法在 for 循环中添加更多范围,好像 i>150 然后 sample_data.append(population_data[i] ) 将超出范围。

我想要实现的是: if sample_lenth==len(sample_data): then break else 将 i 值更改为 1-150 之间的任何值,循环继续

任何帮助!

【问题讨论】:

  • 您可以使用 ՛random.sample()՛ 从数据集中提取样本。
  • 谢谢,@luca.vercelli 是的,可以的,不过我更喜欢break和else操作: else: i=10 #(基本上是想改i的值,低于确切值)打印(i)我在这里做错了什么,

标签: python for-loop break


【解决方案1】:

恐怕for...else 构造与您要查找的内容无关。

在 for 循环结束后,else 子句最多执行一次。

参见例如https://book.pythontips.com/en/latest/for_-_else.html

您不能在for 循环内更改i 变量。可能您想使用while 循环。参见例如How to change index of a for loop?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 2019-01-16
    • 2014-12-04
    • 1970-01-01
    • 2022-08-07
    • 2021-05-23
    相关资源
    最近更新 更多