繁体   English   中英

Python:将列表中的元素替换为另一个元素

[英]Python: Replace an element in a list with an element from another

我有一个列表,但是用户输入的单元格很多。 假设用户输入4,则列表将包含4个0: list_1 = [0,0,0,0]

现在,还会询问用户要用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
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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