【问题标题】:Wanting 1 output vs multiple in loops想要 1 个输出与多个循环
【发布时间】:2021-12-30 17:35:22
【问题描述】:

我正在编写一个函数,它接受一个“主要”并通过字典中的值对其进行迭代。正确的输出是如果专业在值中,则打印键(1 个实例),如果不只是将“专业”打印为上层()。但我不知道如何编写它来检查每个值,但如果值在其中,则只打印键的一个实例,而不是其他 16 个值的多种大写格式。

输入: 教育, 计算机科学

输出: 教育, 比较

student_majors_vari = {
'COMP':['compsci','comp sci','computer sci','computer science'],
'CMPE':['compeng', 'comp eng', 'computer eng', 'computer engineering'],
'EE':['eleceng', 'elec eng', 'elec engineering', 'electrical engineering'],
'MATH':['mathsci', 'math sci', 'mathematical sci', 'mathmatical sciences', 'mathematics']
}

def get_major_code(major):
  for univ_majors in student_majors_vari:
    values = student_majors_vari[univ_majors]
    for v in values:
        if major == v or major == values:
            print(univ_majors)
        else:
            print(major.upper())

【问题讨论】:

  • 请提供示例输出

标签: python list loops dictionary nested


【解决方案1】:

您应该使用dict.items() 方法循环遍历键/值对,然后使用in 运算符查看major 是否在values 列表中。另外,我会 return 函数中的值来停止循环并防止重复。

这是伪代码:

def get_major_code(major):
    # Loop through .items() of the dict
        # Check if the major is in the values list
            # If so, return the univ_majors
            # Otherwise, return the major.upper()

这似乎是一个硬件任务,所以看看你是否可以从那个描述中做到这一点。

【讨论】:

  • 我已经更新了它并让它像我需要的那样打印单个输出,但它只适用于 COMP 的值。其他键的其余值返回 else 循环。 for univ_majors, values in student_majors_vari.items(): if major in values: return print(univ_majors) elif major in univ_majors: return print(univ_majors) else: return print(major.upper()
  • 你为什么有elif?只有两个条件吧?有些东西要么在专业,要么不在。还有什么可以比较的?
  • 我的条件错了!我不需要elif!谢谢
猜你喜欢
  • 2023-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多