[Tutor] Please Help

Arijit Ukil arijit.ukil at tcs.com
Fri Mar 22 08:24:01 CET 2013


Hi,

I have another small problem. Pls help.

I have written the following code:

f = open ("digi_2.txt", "r+")
lines = f.readlines()
for line in lines:
    number_list = []
    for number in line.split(','):
        number_list.append(float(number))

s_data = []
for i in range(len(number_list)):
    if number_list[i] > 5:
        s_data = number_list[i]

print 'Data val:', s_data


The problem is: it is printing only the last value, not all the values. In 
this case '10', not '9,8,6,10'.



Regards,
Arijit Ukil
Tata Consultancy Services
Mailto: arijit.ukil at tcs.com
Website: http://www.tcs.com
____________________________________________
Experience certainty.   IT Services
                        Business Solutions
                        Outsourcing
____________________________________________



From:
Amit Saha <amitsaha.in at gmail.com>
To:
Arijit Ukil <arijit.ukil at tcs.com>
Cc:
tutor at python.org
Date:
03/21/2013 05:30 PM
Subject:
Re: [Tutor] Please Help



Hi Arijit,

On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil <arijit.ukil at tcs.com> wrote:
>
> I am new to python. I like to calculate average of the numbers by 
reading
> the file 'digi_2.txt'. I have written the following code:
>
> def average(s): return sum(s) * 1.0 / len(s)
>
> f = open ("digi_2.txt", "r+")
>
> list_of_lists1 = f.readlines()
>
>
> for index in range(len(list_of_lists1)):
>
>
>     tt = list_of_lists1[index]
>
>     print 'Current value :', tt
>
> avg =average (tt)
>
>
> This gives an error:
>
> def average(s): return sum(s) * 1.0 / len(s)
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
> I also attach the file i am reading.
>
>
>
> Please help to rectify.

The main issue here is that when you are reading from a file, to
Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' +
5 isn't (for example). Hence, besides the fact that your average
calculation is not right, you will have to 'convert' the string to an
integer/float to do any arithmetic operation on them. (If you know C,
this is similar to typecasting). So, coming back to your program, I
will first demonstrate you a few things and then you can write the
program yourself.

If you were to break down this program into simple steps, they would be:

1. Read the lines from a file (Assume a generic case, where you have
more than one line in the file, and you have to calculate the average
for each such row)
2. Create a list of floating point numbers for each of those lines
3. And call your average function on each of these lists

You could of course do 2 & 3 together, so you create the list and call
the average function.

So, here is step 1:

with open('digi.txt','r') as f:
    lines = f.readlines()

Please refer to
http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
for an explanation of the advantage of using 'with'.

Now, you have *all* the lines of the file in 'lines'. Now, you want to
perform step 2 for each line in this file. Here you go:

for line in lines:
    number_list = []
    for number in line.split(','):
        number_list.append(float(number))

 (To learn more about Python lists, see
http://effbot.org/zone/python-list.htm). It is certainly possible to
use the index of an element to access elements from a list, but this
is more Pythonic way of doing it. To understand this better, in the
variable 'line', you will have a list of numbers on a single line. For
example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they
are separated by a ',' ? To get each element, we use the split( )
function, which returns a list of the individual numbers. (See:
http://docs.python.org/2/library/stdtypes.html#str.split). And then,
we use the .append() method to create the list. Now, you have a
number_list which is a list of floating point numbers for each line.

Now, step 2 & 3 combined:

for line in lines:
    number_list = []
    for number in line.split(','):
        number_list.append(float(number))
    print average(number_list)

Where average( ) is defined as:

def average(num_list):
    return sum(num_list)/len(num_list)



There may be a number of unknown things I may have talked about, but i
hope the links will help you learn more and write your program now.

Good Luck.
-Amit.


--
http://amitsaha.github.com/


=====-----=====-----=====
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130322/bcf827ca/attachment-0001.html>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: digi_2.txt
URL: <http://mail.python.org/pipermail/tutor/attachments/20130322/bcf827ca/attachment-0001.txt>


More information about the Tutor mailing list