从列表中删除一个元素和对应的值

Removing an element from a list and a corresponding value

myList = ['a', 'b', 'c']
myOtherList = [1, 2, 3]

如果我从 myList 中选择了一个元素,我如何从 myOtherList 中删除相应的值。我随机从 myList 中选择元素,需要确保从 myOtherList 中删除相应的值。

myList中随机选择一个索引会更容易。

from random import randint

myList = ['a', 'b', 'c']
myOtherList = [1, 2, 3]

index = randint(0, len(myList)-1)

del myList[index]
del myOtherList[index]

但是如果您在选择项目时遇到困难,只需使用... index 函数获取项目的索引!

index = myList.index(chosen_element)

选择项目,然后压缩列表,使它们对应,例如

listA = [1,2,3,4]
listB = [a,b,c,d]

joinedlist = zip(listA,listB)

indexpick = randomindexpicker()  # lets assume that this is '2'

del joinedlist[indexpick]

listA, listB = zip(*joinedlist)

这应该给你

listA = [1,2,4]
listB = [a,b,d]