[Tutor] (no subject)

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Mon Jul 21 09:52:44 CEST 2014


On 21.07.2014 01:48, LN A-go-go wrote:> Dear Gurus,
 > Thank-you thank-you, one more time, thank-you.
 > I am over that hurdle and have the other: converting the list of
 > characters that was just created by the split - into integers so I can
 > manipulate them.  I was trying to convert to a string, then to
 > integers.  I have been scouring the web for casting integers, converting
 > to strings and also trying to look up the error messages: I
 > apologize for the mess - I was trying everything.
 >
 > Sigh,
 > Python in the hands of the naïve
 >
 > LN.
 >
 >>>> numlist = data_value
 >>>> numlist
 > ['36', '39', '39', '45', '61', '54', '61', '93', '62', '51', '47', '72',
 > '54', '36', '62', '50', '41', '41', '40', '62', '62', '58', '57', '54',
 > '49', '43', '47', '50', '45', '41', '54', '57', '57', '55', '62', '51',
 > '34', '57', '55', '63', '45', '45', '42', '44', '34', '53', '67', '58',
 > '56', '43', '33']
 >>>> print sum(numlist)
 > Traceback (most recent call last):
 >    File "<pyshell#38>", line 1, in <module>
 >      print sum(numlist)
 > TypeError: unsupported operand type(s) for +: 'int' and 'str'
 >>>> orange_drinkers = int(data_value)

First thing you have to do in programming is to state your problem 
correctly: you do not want to convert your list to an integer 
representation.
This is what you are attempting in your last line above: convert the 
data_value list to a single integer, and obviously, that cannot work.

Instead, what you want to do is to convert every element in your list to 
an integer. You already know how to do this in a for loop:

int_list = []
for element in data_value:
     int_list.append(int(element))

However, for simple transformations like this, Python has a very 
powerful construct called list comprehensions (read about them here: 
https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions 
, they're really great), which allow you to replace the for loop with a 
simple:

int_list = [int(element) for element in data_value]

You can even combine the comprehension with sum on one line like this:

print sum([int(element) for element in data_value])

Yet, while all of the above should help you learn Python programming 
patterns, your original code already had the best solution:

data_value = []
..
while True:
     line = infile.readline()
     if not line: break
     ..
     States, OJ = string.split(line)
     XNUM = int(OJ)
     ..
     data_value.append(XNUM)

, i.e. converting each value to an int before adding it to the original 
list.

Best,
Wolfgang



More information about the Tutor mailing list