【问题标题】:Cannot access tuple elements through the for in range loop无法通过 for in range 循环访问元组元素
【发布时间】:2020-11-29 03:23:28
【问题描述】:

我写了一个小python程序 使用for in range循环来组合subjects和score的元组内容 打印时显示 我希望达到以下效果

Chinese score: 85 points
Math score: 79 points
English score: 93 points

而是这个错误结果

Chinese score:  points 85
Math score:  points 79
English score:  points 93

它的中文、数学和英文都打印错了三遍 然后将乐谱印在乐谱的外侧 希望大家可以帮忙 如何使用for in range循环来组合元组的内容 如何在打印中显示? 我的代码:

subjects=["Chinese scores: points","Mathematics scores: points","English scores: points"]
score=["85","79","93"]
for subs in range(len(subjects)):
   for scs in range(len(score)):
    print(subjects[subs],score[scs])

谢谢大家

【问题讨论】:

    标签: python


    【解决方案1】:

    在您的代码中,嵌套 for 循环意味着每个主题都有三个分数,并且您已经在分数之前设置了“分数:分”。

    subjects=["Chinese","Mathematics","English"]
    score=["85","79","93"]
    for index in range(len(subjects)):
        print(f'{subjects[index]} score: {score[index]} points')
    
    Chinese score: 85 points
    Mathematics score: 79 points
    English score: 93 points
    

    也许你可以使用 zip 来实现它,

    subjects = ["Chinese","Mathematics","English"]
    scores = [85, 79, 93]
    for subject, score in zip(subjects, scores):
        print(f'{subject} score: {score} points')
    
    Chinese score: 85 points
    Mathematics score: 79 points
    English score: 93 points
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-24
      • 2021-05-13
      • 2021-10-30
      • 2013-10-29
      • 2019-08-11
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多