wulymammoth
wulymammoth

Reputation: 9011

Learning Python: Changing value in list based on condition

Sorry for the very basic question, but this is actually a 2-part question:

  1. Given a list, I need to replace the values of '?' with 'i' and the 'x' with an integer, 10. The list does not always have the same number of elements, so I need a loop that permits me to do this.

    a = ['1', '7', '?', '8', '5', 'x']
    
  2. How do I grab the index of where the value is equal to '?'. It'd be nice if this show me how I could grab all the index and values in a list as well.

Upvotes: 3

Views: 18723

Answers (7)

Matthias Beaupère
Matthias Beaupère

Reputation: 1827

You can now use lambda

# replace occurrences of ?
a = map(lambda x: i if x == '?' else x, a)
# replace occurrences of x
a = list(map(lambda x: 10 if x == 'x' else x, a))

Upvotes: 2

DSM
DSM

Reputation: 353009

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.

Upvotes: 5

ThiefMaster
ThiefMaster

Reputation: 318488

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('?').

Upvotes: 6

kindall
kindall

Reputation: 184091

a = ['1', '7', '?', '8', '5', 'x']
for index, item in enumerate(a):
    if item == "?":
       a[index] = "i"
    elif item == "x":
       a[index = 10

print a

Upvotes: 1

D.Shawley
D.Shawley

Reputation: 59553

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

Upvotes: 3

yedpodtrzitko
yedpodtrzitko

Reputation: 9359

it is function called 'index':

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

Upvotes: 2

David Robinson
David Robinson

Reputation: 78590

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('?')

Upvotes: 4

Related Questions