我有以下列表:,它存储索引引用(从文件读入)。
easy_answers=[row[ca],row[1],row[2],row[3],row[4]]
示例值:
row[ca] = 1 #this is a flag that points to the right response, in this case row1 which is a
row[1] = a
row[2] = b
row[3] = c
and so on
我想要做的只是检查列表以查看任何保留列表元素的索引是否相同(重复),如果是,则删除重复索引(但保留行[ca]值,因为这是正确的答案)
在上面的示例中,预期输出将为:
easy_answers=[row[ca],row[1],row[2],row[3],row[4]]
#we know from the values that row[ca] = 1 and row[1] =1, so remove row[1]
..所以最终的输出是:
easy_answers=[row[ca],row[2],row[3],row[4]]
代码
在处理只是值时从列表中删除副本很简单,但是如何更改下面的代码以搜索索引号所保持的值以实现相同的目的?
ca=int(row[5]) #this is the right resopnse for the question
easy_answers=[row[ca],row[1],row[2],row[3],row[4]]
if row[ca] in easy_answers:
easy_answers.remove(row[ca])
答案 0 :(得分:1)
除了添加然后进行重复数据删除之外,您最好还是删除正确的答案,然后再重新添加。
import random
correct_answer = 2
num_choices = 3
possibles = [1, 2, 3, 4]
#
if len(possibles) != num_choices:
possibles.remove(correct_answer)
random.shuffle(possibles)
possibles = possibles[:num_choices - 1]
possibles.append(correct_answer)
random.shuffle(possibles)
答案 1 :(得分:0)
此函数只是再次创建列表,但如果它们已经存在,则不附加值。所以它永远不会删除CA如果它始终是第一个。
easy_answers = [*values*]
def delete_duplicates_from_list(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
delete_duplicates_from_list = (easy_answers)