Ich weiß, dass es andere Fragen zu diesem Thema gibt; Es ist mir jedoch nicht gelungen, diese Antworten in meinen Code zu übernehmen. Was ich benötige, ist das Sortieren des Wörterbuchs in meiner zweiten und dritten Druckfunktion, die das Wörterbuch nach der Schlagreihenfolge sortieren würde, was der mittlere Wert im Wörterbuchcode ist, z. ['DH', , 299]. Mein Code ist wie folgt:Ich habe Schwierigkeiten beim Sortieren eines Wörterbuchs nach Wert
def main():
print('Rays Starters','\n')
starters = {'DeJesus': ['DH', 6, 299],
'Loney': ['1B', 4, 222],
'Rivera': ['C', 9, 194],
'Forythe': ['2B', 5, 304],
'Souza Jr': ['RF', 2, 229],
'Longoria': ['3B', 3, 282],
'Cabrera': ['SS', 7, 214],
'Kiermaier': ['CF', 1, 240],
'Guyer': ['LF', 8, 275]}
for key, value in starters.items():
print(key, value)
print('\n')
print("Today's lineup", '\n')
for key, value in (starters.items()):
print('Batting {}: {} {}, current avg: {}'.format(value[1], value[0], key, value[2]))
print('\n')
print('Lineup change', '\n')
del starters['DeJesus']
del starters['Rivera']
starters2 = {'Wilson': ['C', 9, 152], 'Bechham': ['DH', 6, 200]}
starters.update(starters2)
for key, value in starters.items():
print('Batting {}: {} {}, curent avg: {}'.format(value[1], value[0], key, value[2]))
main()
Als Referenz meine aktuelle Ausgabe ist:
Rays Starters
Forythe ['2B', 5, 304]
Loney ['1B', 4, 222]
Longoria ['3B', 3, 282]
Kiermaier ['CF', 1, 240]
Guyer ['LF', 8, 275]
Rivera ['C', 9, 194]
DeJesus ['DH', 6, 299]
Cabrera ['SS', 7, 214]
Souza Jr ['RF', 2, 229]
Today's lineup
Batting 5: 2B Forythe, curent avg: 304
Batting 4: 1B Loney, curent avg: 222
Batting 3: 3B Longoria, curent avg: 282
Batting 1: CF Kiermaier, curent avg: 240
Batting 8: LF Guyer, curent avg: 275
Batting 9: C Rivera, curent avg: 194
Batting 6: DH DeJesus, curent avg: 299
Batting 7: SS Cabrera, curent avg: 214
Batting 2: RF Souza Jr, curent avg: 229
Lineup change
Batting 5: 2B Forythe, curent avg: 304
Batting 9: C Wilson, curent avg: 152
Batting 4: 1B Loney, curent avg: 222
Batting 3: 3B Longoria, curent avg: 282
Batting 1: CF Kiermaier, curent avg: 240
Batting 8: LF Guyer, curent avg: 275
Batting 6: DH Bechham, curent avg: 200
Batting 7: SS Cabrera, curent avg: 214
Batting 2: RF Souza Jr, curent avg: 229
die schön gearbeitet. Also das "x: x [1] [1]", wie kann man diesen bestimmten Wert nennen, und nicht die Batting-Durchschnitt # (ex. 300), die viel höhere Zahlen im Code sind. –
Extrahieren der 'key_func' ist eine gute Idee, wenn Sie Unittests schreiben können. Guido machte die Lambda-Syntax aus einem bestimmten Grund hässlich –