gpt4 book ai didi

python - 比较 2 个列表并将索引和值返回给第三个列表

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:00 25 4
gpt4 key购买 nike

answer_list = ['a', 'b', 'c', 'd']
student_answers = ['a', 'c', 'b', 'd']
incorrect = []

我想比较列表 1 中的索引 0 和列表 2 中的索引 0,如果它们相等,则移动到比较每个列表中的索引 1。

在此实例中,列表 1 中的索引 1 != 列表 2 中的索引 1,因此我想将索引+1 和不正确的学生答案(在本例中为字母 c)附加到空列表中。这是我尝试过的 - 未成功。

def main():
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'c', 'b', 'd']
incorrect = []

for x in list1:
for y in list2:
if x != y:
incorrect.append(y)

print(incorrect)

main()

最佳答案

由于您需要逐个元素地比较列表,因此您还需要同时迭代这些列表。有不止一种方法可以做到这一点,这里有一些。

内置函数zip允许您迭代多个可迭代对象。这将是我的选择方法,因为在我看来,这是一次遍历多个序列的最简单和最易读的方法。

for x,y in zip(list1, list2):
if x != y:
incorrect.append(y)

另一种方法是使用方法 enumerate :

for pos, value in enumerate(list1):
if value != list2[pos]:
incorrect.append(list2[pos])

Enumerate 负责为您跟踪索引,因此您不需要为此创建一个特殊的计数器。

第三种方法是使用索引遍历列表。一种方法是写:

for pos range(len(list1)):
if list1[pos] != list2[pos]:
incorrect.append(list2[pos])

注意如何通过使用 enumerate 获取开箱即用的索引。

所有这些方法也可以使用列表理解来编写,但在我看来,这更具可读性。

关于python - 比较 2 个列表并将索引和值返回给第三个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com