3

I have a list, whose indices are mostly integer numbers, but occasionally, there are some 'X' entries. I need all of the entries to perform list operations with this list and another list. How can I replace the 'X' entries which are strings with integers zeroes, while keeping the lists the same length.

I've tried using if statements to replace the entry if it is an 'X', but that just gave me a type error.

Example: changing

['X', 'X', 52, 39, 81, 12, 'X', 62, 94]

to

[0, 0, 52, 39, 81, 12, 0, 62, 94]

in which all entries in the second list are int.

4 Answers 4

8

Try to use map to do this:

>>> l= ['X','X',52,39,81,12,'X',62,94]
>>>
>>> map(lambda x:0 if x=="X" else x,l)
[0, 0, 52, 39, 81, 12, 0, 62, 94]

If you're using Python3.x , map() returns iterator, so you need to use list(map()) to convert it to list.

Or use list comprehension:

>>> [i if i!='X' else 0 for i in l]
[0, 0, 52, 39, 81, 12, 0, 62, 94]
Sign up to request clarification or add additional context in comments.

1 Comment

Please note that map function only returns a list in Python2. In Python3, the map function will return an iterator and not a lit.
6

First of all, you need to improve your use of terminologies. The indices are all integers, it is the elements that are a mix of strings and integers.

Solution

l = ['X', 'X', 52, 39, 81, 12, 'X', 62, 94]
l = [0 if element == 'X' else element for element in l]
print(l)

Better Performance Solution, with in-place replace

l = ['X', 'X', 52, 39, 81, 12, 'X', 62, 94]
for i in range(len(l)):
  l[i] = 0 if l[i] == 'X' else l[i]
print(l)

Comments

1

If performance is a concern, you can use numpy:

>>> import numpy as np
>>> a=np.array(['X','X',52,39,81,12,'X',62,94])
>>> a[a=='X']=0
>>> a
array(['0', '0', '52', '39', '81', '12', '0', '62', '94'], 
      dtype='|S2')

Then if you want all ints:

>>> a.astype(int)
array([ 0,  0, 52, 39, 81, 12,  0, 62, 94])

Comments

0

Try this:

for i in range(0,len(list)):
    if list[i] == 'X':
        list.pop(i)
        list.insert(i,0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.