[Tutor] Please Help

Martin A. Brown martin at linux-ip.net
Fri Mar 22 14:33:50 CET 2013


Greetings,

 : I have the following data points.
 : data = [1,2,0,9,0,1,4]
 : I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 
 : (considering index starts at 0)
 : 
 : I have written the following code which is not running:
 : 
 : import math
 : 
 : number_list = [1,2,0,9,0,1,4]
 : 
 : number_list_1 = []
 : for k in range(math.floor(float(len(number_list)/2))):
 :     if (k< math.floor(float(len(number_list)/2))):
 :                 number_list_1[k] = number_list[k*2 + 1]
 : 
 : print 'data: ', number_list_1 

My first thought when I see the above is that you appear to be
taking a circuitous route to the market!  You must really want to
get your exercise on your journey to fetch the list of [2, 9, 1].

My second observation is that the looping over a list using the
technique you showed here (and in your prior mail) is something
that looks more like C or Java.  Looping on an list (array, or any
sort of sequence) is a bit easier here in the lands of Python.
You can simply:

  for item in list_data:
      # -- do something with item

Since you are in the lands of Python (and welcome, by the way),
the Python docs are pretty good (and not overwhelming), and
include some excellent examples, so try reading about sequences
and how to manipulate them at this online doc:

  http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange

Anyway, I think you may benefit from seeing this solution a bit
more Pythonically, so I have offered two different solutions.

-Martin

data = number_list = [1,2,0,9,0,1,4]

# -- you call it 'number_list_1'; I will call it 'outlist'
#
outlist = []
for idx,val in enumerate(data):
    print idx, val
    if 0 == (idx % 2):  # -- skip even entries; do not append
        continue
    outlist.append(val)

print 'loop over enumerate() to get your data: ', outlist

# -- OR, given how simple your operation on the list is, consider
#    learning about slicing; see the standard docs on sequences:
#
#    http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange
#

print 'slice out from your original data: ', data[1::2]

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list