Reputation: 9011
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 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']
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
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
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
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
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
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
Reputation: 9359
it is function called 'index':
>>> a = ['1', '7', '?', '8', '5', 'x']
>>> a.index('?')
2
Upvotes: 2
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