Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:在预定义索引处向列表添加值_Python_List - Fatal编程技术网

Python:在预定义索引处向列表添加值

Python:在预定义索引处向列表添加值,python,list,Python,List,我有一份清单(清单) 我需要创建另一个与列表(checkColumn)长度相同的列表,并在索引列表(indexList)中定义的位置添加1,索引列表中未定义的位置应为0 输入: 期望输出: 我一直在尝试下面的代码,但得到的输出是[1,1] for a in len(aList): if a == indexList[a]: checkColumn = checkColumn[:a] + [1] + checkColumn[a:] else: che

我有一份清单(清单) 我需要创建另一个与列表(checkColumn)长度相同的列表,并在索引列表(indexList)中定义的位置添加1,索引列表中未定义的位置应为0

输入:

期望输出:

我一直在尝试下面的代码,但得到的输出是[1,1]

for a in len(aList):
    if a == indexList[a]:
        checkColumn = checkColumn[:a] + [1] + checkColumn[a:]
    else:
        checkColumn = checkColumn[:a] + [0] + checkColumn[a:]
我尝试过使用checkColumn.insert(a,1),得到了相同的结果。
谢谢你的帮助

您可以使用列表在一行中完成此操作:

aList = [70, 2, 4, 45, 7 , 55, 61, 45]
indexList = [0, 5, 1]

checkColumn = [1 if a in indexList else 0 for a in range(len(aList))]
print(checkColumn)
# [1, 1, 0, 0, 0, 1, 0, 0]

您可以使用列表在一行中完成此操作:

aList = [70, 2, 4, 45, 7 , 55, 61, 45]
indexList = [0, 5, 1]

checkColumn = [1 if a in indexList else 0 for a in range(len(aList))]
print(checkColumn)
# [1, 1, 0, 0, 0, 1, 0, 0]
这有帮助吗

首先,用0初始化checkColumn

checkColumn = [0] * len(aList)
然后,循环索引列表并更新checkColumn

for idx in indexList:
    checkColumn[idx] = 1
干杯

这有帮助吗

首先,用0初始化checkColumn

checkColumn = [0] * len(aList)
然后,循环索引列表并更新checkColumn

for idx in indexList:
    checkColumn[idx] = 1

干杯

我能问你为什么需要这个吗?你能描述一下导致这个解决方案的问题吗?列表是所有项目的id,其中我已经确定了坏项目的索引,并将其放入索引列表中。现在我想在另一个列表中标记(检查)坏的项目(1)和好的项目(0)。这重新描述了您提出的问题。而不是它是如何产生的。我认为可能有一个更简单的解决方案来解决你在更高层次上所做的事情。祝你好运:)我能问你为什么需要这个吗?你能描述一下导致这个解决方案的问题吗?列表是所有项目的id,其中我已经确定了坏项目的索引,并将其放入索引列表中。现在我想在另一个列表中标记(检查)坏的项目(1)和好的项目(0)。这重新描述了您提出的问题。而不是它是如何产生的。我认为可能有一个更简单的解决方案来解决你在更高层次上所做的事情。祝你好运:)你可以用
int(索引列表中的a)做得更短。
你可以用
int(索引列表中的a)做得更短。