Jump to content

Converting Lists to Integers

- - - - -

  • Please log in to reply
1 reply to this topic

#1
restin84

restin84

    Learning Programmer

  • Members
  • PipPipPip
  • 53 posts
If I do this in the python interpreter...
>>> args = ['1996','2000']
>>> print args
['1996', '2000']
>>> intArgs = [int(x) for x in args]
>>> print intArgs
[1996, 2000]
>>> a = intArgs[1] + 1
>>> print a
2001



...everything is fine.


But if I do this in a '.py' file....
args = getopt.getopt(sys.argv[1:], '')

intArgs = [int(x) for x in args]



...I get this error...
Traceback (most recent call last):
  File "./assignment6.py", line 21, in  <module>
    intArgs = [int(x) for x in args]
TypeError: int() argument must be a string or a number, not 'list'

I guess my question is how can I convert a list item to an integer? I have some experience with C++ and Java (in an educational setting) but I am completely new to Python

#2
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 890 posts
  • Location:::1
Seems some arguments are lists (if you read the error). What arguments are you passing?

Also, check out map function.
str_list = ["1", "2", "3"]
int_list = map(int, str_list)

A conclusion is where you got tired of thinking.
#define class struct    // All is public.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users