简体   繁体   中英

Python - Converting an int to a string only works once?

I am learning how to manipulate lists in python, so I decided to make up an exercise to see if I could do an implementation of the "fizzbuzz" game with only using python's list operations as shown below:

#Fizzbuzz Implementation

def fizzbuzz(L):
    # L is a list of integers in order 
    for i in L[2::3]:
        L[i-1] = str(L[i-1])
        L[i-1] = L[i-1].replace(L[i-1],'')
        #No exception thrown here

    for i in L[4::5]:
        L[i-1] = str(L[i-1]) #Exception on this line
        L[i-1] = L[i-1].replace(L[i-1],'')

    for i in L[2::3]:
        L[i-1] += 'fizz'

    for i in L[4::5]:
        L[i-1] += 'buzz'

    return L[:]

L = list(range(1,101))
L[:] = fizzbuzz(L)

I tried to convert the integers in the list of interest into empty strings, then append strings to them, however I get a TypeError: unsupported operand type(s) for -: 'str' and 'int'

I noticed that the first loop happens with no issues, but the exception is always thrown on the second loop. This happens even if I switch the order of the loops.

Can someone explain what the exception is being thrown for and why it only happens on the second loop?

Once you do the first loop, some of the elements in the list are strings, and you can no longer use them as indices to access the list. You are also doing some strange things, like casting an element to a string and then replacing the whole thing with the empty string instead of just assigning an empty string, and calling a function that mutates a list, returns the list, and reassigns all those elements back to itself. Instead, keep track of indices with enumerate , remembering to start at 1 and multiply the index by the slice's step value.

def fizzbuzz(L):
    for i,val in enumerate(L[2::3], start=1):
        L[i*3-1] = ''
    for i,val in enumerate(L[4::5], start=1):
        L[i*5-1] = ''
    for i,v in enumerate(L[2::3], start=1):
        L[i*3-1] += 'fizz'
    for i,v in enumerate(L[4::5], start=1):
        L[i*5-1] += 'buzz'

L = list(range(1,101))
fizzbuzz(L)

unsupported operand type(s) for -: 'str' and 'int'

The Python interpreter is saying you're trying to subtract a string and an integer. Like: "123" - 1 In the first loop, you've converted the integers to strings, so if you want to do subtraction in the second loop, you'll need to convert the strings back to integers. Like: int("123") - 1

L[i-1] = str(L[int(i)-1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM