How to make dictionary to maintain orderly --- Python data structures and algorithms related issues and solving skills

   actual case:

   A programming competition system, the disintegration of the contestants programming for timing, after players complete the title, it records the player to use a dictionary when disintegration, so the players after the game by the name of the query results

  { 'Lilei' :( 2,43), 'HanMei' :( 5,52), 'Jim' :( 1,39) ...}

      After the game, adjustment shall be ranked in the order printed players score, how to achieve?

 

from collections Import OrderedDict
 # shuffle shuffle function, the order list can be disrupted 
from Random Import shuffle 

'' ' 
use the standard library collections in OrderedDict 
to OrderedDict Alternate dictionary Dict, in turn, players score into OrderedDict 
' '' 

the Players = List ( ' ABCDEFGH ' ) 
shuffle (Players) 
Print (Players)
 # [ 'C', 'B', 'D', 'A', 'F', 'E', 'H', 'G'] 
OD = OrderedDict ()
 # simple simulation, ranking order 
for i, the p- in the enumerate (the Players, 1 ):
    of [p] = and
 print(OD)
 # OrderedDict ([( 'B',. 1), ( 'A', 2), ( 'F',. 3), ( 'C',. 4), ( 'D',. 5), ( 'G ',. 6), (' H ',. 7), (' E ',. 8)]) 
# write Interface - The name of the query results 


DEF query_by_name (D, name):
     # according to the key - the value 
    return D [name] 


# testing - The key values - i.e., under the name - taken results 
Print (query_by_name (OD, ' C ' ))
 Print (query_by_name (OD, ' B ' ))
 '' ' 
in accordance with the order - the name of the query, or according to the range, the query name 
    iter (od) does not support the indexing and slicing operations 
in the iterative tool itertoools, the introduction of islice slice 
'' '
from itertools import islice
#islice works: sequentially iteration preceding the iteration objects 
# examples - iteration starts from 0, the value outside the range discarded 
isTest = islice (Range (10),. 3,. 6 )
 Print (List (isTest))
 # [. 3,. 4 ,. 5] 
isOd = islice (OD,. 3,. 6 )
 Print (List (isOd))
 # [ 'E', 'H', 'A'] 


# The ranking value, the inquiry key key 
DEF query_by_order (D, A, B = None): 
    a - =. 1
     # if you only want a data query 
    IF B IS None:
         # B + a =. 1, a description that is accessible to only the (a, a +. 1) 
        B = a +. 1 return List (islice ( OD, A, B)) # test Print (query_by_order (OD,. 4
    



))
print(query_by_order(od, 3, 6))
# ['g']
# ['c', 'g', 'f', 'e']

 

 The above-mentioned problem-solving ideas, based on python3.5

   python3.6, a built-in dictionary dict behavior has been consistent with OrderedDict, you can use dict

 But in order to code-compatible, it is recommended to use OrderedDict function.

 

Guess you like

Origin www.cnblogs.com/goddog1024/p/11301123.html