Python字典/循环输出

3
  • Make a dictionary for nine Tampa Bay Rays that are given. Use the player names as keys and a list for each value.
  • Each value list should hold the position played by the player, the batting order, and current batting average. See above.
  • When the dictionary is complete, use a for loop to display the dictionary keys and values. This is what I got for this
  • Next, use loop(s) to print the "lineup" (the dictionary in batting order). This is the step I need some help with, not sure how I go about doing an order for a dictionary like so. A list made more sense to me but that is not the question.

      main():
          rays_players = { 'DeJesus': ['DH', 6, 299],
                     'Loney': ['1B', 4, 222],
                     'Rivera': ['C', 9, 194],
                     'Forsythe': ['2B', 5, 304],
                     'Souza Jr': ['RF', 2, 229],
                     'Longoria': ['3B', 3, 282],
                     'Cabrera': ['SS', 7, 214],
                     'Kiermaier': ['CF', 1, 240],
                     'Guyer': ['LF', 8, 274] }
    
        for key in rays_players:
            print(key, rays_players[key])
       main()
    

这是我一直在尝试的,但它没有起作用,我对此非常陌生:

for key in sorted(rays_players.items(), key=lambda v: (v)):
    print ("%s: %s" % (key))

第四步应该是这样的:

击球手1:中外野手Kiermaier,目前平均安打率:240

击球手2:右外野手Souza Jr,目前平均安打率:229

击球手3:三垒手Longoria,目前平均安打率:282

击球手4:一垒手Loney,目前平均安打率:222

击球手5:二垒手Forsythe,目前平均安打率:304

击球手6:指定打击DeJesus,目前平均安打率:299

击球手7:游击手Cabrera,目前平均安打率:214

击球手8:左外野手Guyer,目前平均安打率:274

击球手9:捕手Rivera,目前平均安打率:194


“Bating order” 是什么意思? - Ionut Hulub
1个回答

7
希望这能帮到您:
rays_players = {'DeJesus': ['DH', 6, 299],
                'Loney': ['1B', 4, 222],
                'Rivera': ['C', 9, 194],
                'Forsythe': ['2B', 5, 304],
                'Souza Jr': ['RF', 2, 229],
                'Longoria': ['3B', 3, 282],
                'Cabrera': ['SS', 7, 214],
                'Kiermaier': ['CF', 1, 240],
                'Guyer': ['LF', 8, 274]}

for key, value in sorted(rays_players.items(), key=lambda v: v[1][1]):
    print("Batting {}: {} {}, current avg: {}".format(value[1], value[0], key, value[2]))

太棒了!谢谢!我很高兴我至少在我尝试的代码中有一些相同的单词 xD - Kate Bliss

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接