pe...@ifoley.id.au wrote: > Hi List, > > I am new to Python and wondering if there is a better python way to do > something. As a learning exercise I decided to create a python bash > script to wrap around the Python Crypt library (Version 2.7). > > My attempt is located here - https://gist.github.com/pjfoley/5989653 > > I am trying to wrap my head around list comprehensions, I have read the > docs at > http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions > and read various google results. I think my lack of knowledge is making > it difficult to know what key word to search on. > > Essentially I have this list of tuples > > # Tuple == (Hash Method, Salt Length, Magic String, Hashed Password > # Length) > supported_hashes=[('crypt',2,'',13), ('md5',8,'$1$',22), > ('sha256',16,'$5$',43), ('sha512',16,'$6$',86)] > > This list contains the valid hash methods that the Crypt Library supports > plus some lookup values I want to use in the code. > > I have managed to work out how to extract a list of just the first value > of each tuple (line 16) which I use as part of the validation against the > --hash argparse option. > > My Question. > > Looking at line 27, This line returns the tuple that mataches the hash > type the user selects from the command line. Which I then split the > seperate parts over lines 29 to 31. > > I am wondering if there is a more efficient way to do this such that I > could do: > > salt_length, hash_type, expected_password_length = [x for x in > supported_hashes if x[0] == args.hash] > > From my limited understanding the first x is the return value from the > function which meets the criteria. So could I do something like: > > ... = [(x[0][1], x[0][2], x[0][3]) for x in supported_hashes if x[0] == > args.hash] > > I am happy to be pointed to some documentation which might help clarify > what I need to do. > > Also if there is anything else that could be improved on with the code > happy to be contacted off list.
Every time when you have to look up something you should think 'dict', and I expect that pretty that will happen automatically. Also, to split a tuple into its items you can "unpack" it: triple = (1, 2, 3) one, two, three = triple assert one == 1 and two == 2 and three == 3 So: supported_hashes = { "crypt": (2, "", 13), "md5": (8, "$1$", 22), ... } ... parser.add_argument( '--hash', default='sha512', choices=supported_hashes, # accept the keys help='Which Hash function to use') ... salt_length, hash_type, expected_password_length = supported_hashes[args.hash] ... -- http://mail.python.org/mailman/listinfo/python-list