JBarnes
JBarnes

Reputation: 11

How to exclude 1 item in a list from for...in... loop

I am writing a function to infect and cure a city, except I always want city[0] to remain as infected. all the cities are part of a list.

def sim_step(cities , p_spread , p_cure):
    for city in cities:
        if city[1] == True and numpy.random.rand() < p_spread:
            zombify(my_world , cities[numpy.random.randint(city[3])])
        if city[1] == False and numpy.random.rand() < p_cure:
            cure(my_world , cities[numpy.random.randint(city[3])])

Upvotes: 1

Views: 139

Answers (3)

Sorin Dragan
Sorin Dragan

Reputation: 540

From what I understood, you just have to make sure that you won't cure the first city (cities[0]).

    ...
    if city[1] == False and numpy.random.rand() < p_cure:
        idx = numpy.random.randint(city[3])
        if idx == 0:
            continue
        cure(my_world , cities[idx])

Upvotes: 0

JimShapedCoding
JimShapedCoding

Reputation: 917

Its too hard to understand with those kind of naming methods.

However , from what i understand, your problem is to collect always the first element while running through your cities list.

I recommend using enumerate methods so you can run through both index of an element, the element itself

Enumerate methods allows to run through list of indexes and the list elements.


def sim_step(cities , p_spread , p_cure):
    for index,city in enumerate(cities):
        if city[1] == True and numpy.random.rand() < p_spread:

            zombify(my_world , cities[numpy.random.randint(city[3])])

        if city[1] == False and numpy.random.rand() < p_cure:
            cure(my_world , cities[numpy.random.randint(city[3])])

        if index == 0:
            remain_infected()

See here more about the enumerate method: https://docs.python.org/3/library/functions.html#enumerate

Upvotes: 0

dmigo
dmigo

Reputation: 3029

You can do that like that:

def sim_step(cities , p_spread , p_cure):
    for city in cities[1:]:
        if city[1] == True and numpy.random.rand() < p_spread:
            zombify(my_world , cities[numpy.random.randint(city[3])])
        if city[1] == False and numpy.random.rand() < p_cure:
            cure(my_world , cities[numpy.random.randint(city[3])])

The difference is here: cities[1:]. This is called slice operation. To understand more about it read this answer.

Upvotes: 2

Related Questions