python - 如何从 2 个单独的列表中返回一对索引?
问题描述
我是一个初学者,正在尝试用 Python 练习我的技能。
对于我正在练习的问题,我必须返回一个显示以下配对索引的列表:Girl and Boy Set A、Girl and Boy Set B、Girl and Boy Set C。
如果 Girl = 3,则 Girl 是 Girl A。
如果 Girl = 6,则 Girl 是 Girl B。
如果 Girl = 12,则 Girl 是 Girl C。
如果 Boy = 1,则 Boy 是 Boy A。
如果 Boy = 4,则 Boy 是 Boy B。
如果 Boy = 8,则 Boy 是 Boy 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
解决方案
对于我正在练习的问题,我必须返回一个显示以下配对索引的列表: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)
推荐阅读
- c# - Xamarin:在视图中异步加载图像
- linux - 插入静态链接的二进制文件
- angular - Angular ReactiveFrom 订阅 valueChanges 给出 [object Object]
- spring - 在非 SpringBoot 应用程序中加载 application.properties 文件
- fortran - 比较 Fortran 输出中的 $ 编辑描述符和 Advance="no"
- javascript - 未知的 Javascript 语法含义
- qt - Qt如何按字符更改选定的文本字符
- meteor - Meteor 1.6 Coffeescript:保留字'import'
- docker - E: gnupg, gnupg2 和 gnupg1 好像没有安装,但是这个操作需要其中一个
- javascript - 无法在此代码中获取 this.value