Python:用另一个元素替换列表中的元素
我有一个列表,但是用户输入的单元格很多。所以说用户输入4,这个列表将包含4个0:list_1 = [0,0,0,0]
。Python:用另一个元素替换列表中的元素
现在用户也被问到他想用1代替哪个零(必须选择2)并输入:1 2
。我想list_1[1]
和list_1[2]
改变从0到1
我已经尝试了一些不同的东西,但都不是给我这应该是一个列表[0,1,1,0]
(如果我使用上面的代码)的预期从看跌
任何帮助表示赞赏。
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
为什么这么多downvotes? Marion和我给了OP他们要求的 –
我不知道为什么人们会这样做?只需点击downvote并且没有任何理由提到甚至纠正其错误。 –
当我们的两个代码完美地工作时,这尤其令人讨厌......并且回答OP的问题 –
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
请解释你的答案,而不是只是倾销代码片段。 – lukad
附加代码,请。 – Meccano
你能告诉我们你到目前为止尝试过的吗? –