简体   繁体   English

根据随机生成的数量从列表中删除元素

[英]Deleting elements from list depending on randomly generated number

This function should take a list of viruses like [ATCG, GTAC.....] and a mortalityProb (float between 0 and 1) that represents the chance of a virus to die / get deleted from the list. 此功能应列出[ATCG,GTAC .....]等病毒和代表病毒死亡或从列表中删除的DeathProb(0到1之间浮动)的列表。 It should return a new list with the remaining viruses. 它应该返回包含其余病毒的新列表。 Each of the viruses has an individual chance to die, so with a mortalityProb of say 0.6, there should be around 60% of the viruses remaining. 每种病毒都有单独的死亡机会,因此,如果死亡率为0.6,则大约应保留60%的病毒。

It should be doable in 2 lines (including def kill(viruses, mortalityProb):) and my line of code using list comprehensions. 它应该可以在两行中执行(包括def kill(病毒,deathProb):)和使用列表推导的我的代码行。

def kill(viruses, mortalityProb):
    for i in viruses:
        if random.randint(0, 100) < (mortalityProb * 100):
            del i
    return viruses

This does not quite work, but I can't get a grasp on why. 这不是很有效,但是我无法理解为什么。

One way to do this is viruses.remove(i). 一种做到这一点的方法是viruss.remove(i)。 However, see the various postings on altering a list while you're iterating through it. 但是,在遍历列表时,请参阅有关更改列表的各种文章。

You can make this a one-liner; 您可以将它设为单线; just call random for each virus, and include it if the "saving throw" works. 只需对每种病毒random调用,并在“节省命中率”有效时将其包括在内。

return [i for i in viruses if random.random() < mortalityProb]

For instance: 例如:

>>> viruses = [x for x in range(20)]
>>> [i for i in viruses if random.random() < 0.75]
[0, 1, 3, 6, 7, 9, 10, 11, 12, 13, 15, 17, 18, 19]

BTW, you have your variable misnamed: mortalityProb should describe the chance of the organism dying, not surviving. 顺便说一句,您的变量名错误: mortalityProb应该描述生物死亡的机会,而不是生存的机会。

Because in the for loop "i' is not actually the element in the list. You have to actually change the viruses list. Something like this may work. 因为在for循环中,“ i”实际上不是列表中的元素。您实际上必须更改病毒列表。类似的操作可能有效。

def kill(viruses, mortalityProb):
    for x,i in enumerate(viruses):
        if random.randint(0, 100) < (mortalityProb * 100):
            viruses.pop(x)
    return viruses

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

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