0

I wanted to replace string with an integer so I first tried this

timeupseats=[0,480,480,0]
for n in range(0,4): 
   if timeupseats[n]==0:
       timeupseats[n]='CLOSED'
for n in range(0,4): 
   if timeupseats[n]=='CLOSED':
       timeupseats[n]==0

Because the first code didn't work, I tried this code for the second time and it worked

timeupseats=[0,480,480,0]
for n in range(0,4): #print closed when there is no ticket left
    if timeupseats[n]==0:
        timeupseats[n]='CLOSED'
timeupseats = [0 if i=='CLOSED' else i for i in timeupseats]

What's the difference between the first code and the second code? Why did only the second code work?

2 Answers 2

1

In your first set of code you have this error on the last line : timeupseats[n]==0

You want to set it to 0 (=) not check for equality (==)

Sign up to request clarification or add additional context in comments.

Comments

0

There are many ways to to this. The in my opinion the most robust one would be to first define the values you want to replace, then apply that on each element of the list with ‘map’:

# make some data
ls = list(range(10))
# define values to replace
mapping = {0: 'CLOSED'}
# do replacement 
ls = list(map(lambda x: mapping.get(x, x), ls))
print(ls)

There is also the more explicit, but more difficult to maintain way:

ls = list(range(10))
for i, x in enumerate(ls):
    if x == 0:
        ls[i] = 'CLOSED'

print(ls)   

5 Comments

User all ready created ls which is equal to ['CLOSED', 480, 480, 'CLOSED'] for input [0,480,480,0] , but user is try to get back initial stage
Then just edit the mapping :). I let you figure it out and edit my answer in about 30min.
In questioner last line of code snippet timeupseats[n]==0 instead of comparison, it should be assign
Create a extra logic for that input ls to get back to initial stage
Everything is okk with your both logic :)

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.