Skip to content Skip to sidebar Skip to footer

Learning Python: Changing Value In List Based On Condition

Sorry for the very basic question, but this is actually a 2-part question: Given a list, I need to replace the values of '?' with 'i' and the 'x' with an integer, 10. The list doe

Solution 1:

Write a function for it and use map() to call it on every element:

def _replaceitem(x):
    if x == '?':
        return 'i'
    elif x == 'x':
       return 10
    else:
        return x

a = map(_replaceitem, a)

Note that this creates a new list. If the list is too big or you don't want this for some other reason, you can use for i in xrange(len(a)): and then update a[i] if necessary.

To get (index, value) pairs from a list, use enumerate(a) which returns an iterator yielding such pairs.

To get the first index where the list contains a given value, use a.index('?').


Solution 2:

For 1:

for i in range(len(a)):
    if a[i] == '?':
        a[i] = 'i'
    elif a[i] == 'x':
        a[i] = 10

For 2, what do you mean by "key"? If you mean index:

index = a.index('?')

Solution 3:

Start by reading the Built-in Types section of the Library Reference. I think that you are looking for list.index.


Solution 4:

Only because no one's mentioned it yet, here's my favourite non-for-loop idiom for performing replacements like this:

>>> a = ['1', '7', '?', '8', '5', 'x']
>>> reps = {'?': 'i', 'x': 10}
>>> b = [reps.get(x,x) for x in a]
>>> b
['1', '7', 'i', '8', '5', 10]

The .get() method is incredibly useful, and scales up better than an if/elif chain.


Solution 5:

it is function called 'index':

>>> a = ['1', '7', '?', '8', '5', 'x']
>>> a.index('?')
2

Post a Comment for "Learning Python: Changing Value In List Based On Condition"