首页 > 解决方案 > 如何从 2 个单独的列表中返回一对索引?

问题描述

我是一个初学者,正在尝试用 Python 练习我的技能。

对于我正在练习的问题,我必须返回一个显示以下配对索引的列表:Girl and Boy Set A、Girl and Boy Set B、Girl and Boy Set C。

我已经确定了 Girls 和 Boys 的索引,但我不确定如何将它们配对并打印配对的索引。

这是我的代码:

arr_girls = [3, 6, 12, 3, 6, 12]
arr_boys = [1, 4, 8, 3, 4]

def girls_and_boys (arr_girls, arr_boys):
    for i in arr_girls:
        if i == 3:
            print("Index of Girl A: ", arr_girls.index(3))
        elif i == 6:
            print("Index of Girl B: ", arr_girls.index(6))
        elif i == 12:
            print("Index of Girl C: ", arr_girls.index(12))

    for i in arr_boys:
        if i == 1:
            print("Index of Boy A: ", arr_boys.index(1))
        elif i == 4:
            print("Index of Boy B: ", arr_boys.index(4))
        elif i == 8:
            print("Index of Boy C: ", arr_boys.index(8))

print(girls_and_boys(arr_girls, arr_boys))

预期输出:返回显示以下对的索引的列表:Girl and Boy Set A、Girl and Boy Set B、Girl and Boy Set C。

0,0
1,1
2,2
4,4

标签: pythonarrayspython-3.xlist

解决方案


对于我正在练习的问题,我必须返回一个显示以下配对索引的列表:Girl and Boy Set A、Girl and Boy Set B、Girl and Boy Set C。

我无法真正理解您要做什么,但是从预期的输出中,解决方案可能是确定两个数组的最小长度,然后简单地打印。如果由于您忘记编写而跳过
了预期的输出:(3,3)

arr_girls = [3, 6, 12, 3, 6, 12]
arr_boys = [1, 4, 8, 3, 4]

def girls_and_boys(arr_girls, arr_boys):
    upper_limit = len(arr_girls)
    if len(arr_boys) < upper_limit:
        upper_limit = len(arr_boys)
    for i in range(upper_limit):
        print(i, i)

girls_and_boys(arr_girls, arr_boys)

如果在预期的输出(3,3)中被跳过,因为arr_girls[3]=3并且arr_boys[3]=3解决方案更改为:

def girls_and_boys(arr_girls, arr_boys):
    upper_limit = len(arr_girls)
    if len(arr_boys) < upper_limit:
        upper_limit = len(arr_boys)
    for i in range(upper_limit):
        boy = arr_boys[i]
        girl = arr_girls[i]
        if boy != girl:
            print(i, i)

推荐阅读