Home > Net >  replacing all integers in one list, with strings in another
replacing all integers in one list, with strings in another

Time:07-21

testdeck = ['rock']
finaldeck = ['apple','banana','napalm','ice',5,6,7,8]

def deckhelp(testdeck,finaldeck):
    testnumber = 0 
    testlength = len(testdeck)
    for index, (card, item) in enumerate(zip(testdeck, finaldeck)):
        if isinstance(item, int): #checks if item is an integer
            finaldeck[index] = card
            print(finaldeck)
            testnumber  = 1
            if testnumber == testlength:
                print('done')
                pass

deckhelp(testdeck,finaldeck)

I want rock to replace the 5 located in finaldeck, can't seem to make it happen

CodePudding user response:

This is not an appropriate use of zip() because you only want to iterate through testdeck when you reach the integers in finaldeck.

You also need to use return, not pass, to end the function when you reach the end of testdeck.

def deckhelp(testdeck, finaldeck):
    testindex = 0
    testlength = len(testdeck)
    for index, item in enumerate(finaldeck):
        if isinstance(item, int):
            finaldeck[index] = testdeck[testindex]
            testindex  = 1
            if testindex == testlength:
                print('done')
                return

CodePudding user response:

Zip only works in testdeck and finaldeck have the same length. Instead, you can use something like this:

def deckhelp(testdeck, finaldeck):
    replace_index = 0
    for i, val in enumerate(finaldeck):
        if isinstance(val, int):
            finaldeck[i] = testdeck[replace_index]
            replace_index  = 1
            if replace_index == len(testdeck):
                print("done")
                return
  • Related