[Tutor] if you're interested in the code thus far...

Alan Gauld alan.gauld at btinternet.com
Mon Oct 27 10:20:48 CET 2014


On 27/10/14 03:17, Clayton Kirkwood wrote:

> get_new_list = True
> print(values) 			#[('a', 'Ask'), ('y', 'Dividend Yield')]
> while get_new_list:
>      key_list = input('Please enter space separated keys in the order you
> want: ').split()
>      print(key_list)		#['a', 'y']
>      for key in key_list:
>          print(key)		#a
>          if key not in values[0]:	#I am trying to ensure that 'a' is
> in the first 'column' of values

Are you only interested in the first pair of values or if its in any 
pair? I'll assume the latter. You could do:

[pair for pair in values if key in pair]

Or if you want to be sure you are testing the first element of the pair:

[pair for pair in values if key == pair[0]]

That will return a list of pairs containing your key.
Hopefully that will usually be only one pair...

You can then test for an empty list in you if statement like:

if not [pair for pair in values if key in pair]:

>              print("Error:", key, "not available, start again")
>              get_new_list = True
>              break
>      else: get_new_list = False

If you want to process the pairs containing the key then you could store 
the comprehension result in a variable, say key_pairs or somesuch.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list