简体   繁体   中英

Python: Replace an element in a list with an element from another

I have a list that is however many cells a user inputs. So say the user inputs 4, the list will consist of 4 0's: list_1 = [0,0,0,0] .

Now the user is also asked which of these zeros he wants to replace with a 1 (must pick 2) and enters: 1 2 . I want list_1[1] and list_1[2] to change from 0 to 1.

I have tried a few different things, but none are giving me the expected out put which should be a list [0,1,1,0] (if i was using the above code)

Any help is appreciated.

num_zero = int(input("Please enter the number of 0s")) #note this is python3
list_1 = num_zero*[0] #creates a list with the inputted number of zeroes
indices = input("Enter list indices: i j") #get string with two numbers in it sep by space
indices = indices.split(" ")  # create array with number strings
for s in indices: 
    i = int(s) #turn each number string into an int
    list_1[i] = 1 #set the specified indices of the list of zeroes to 1
num_zero = input('Enter number of zeros you want in a list:')
zero_list = [0 for i in range(num_zero)]
indices = raw_input('Enter the indices you want to convert separated by space:')
index_list = map(int, indices.split())
for i in index_list:
    zero_list[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