By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,293 Members | 1,183 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,293 IT Pros & Developers. It's quick & easy.

converting to an integer

P: 54
I think the elements in my list must not be being read as integers because when I do something like
Expand|Select|Wrap|Line Numbers
  1. >>> for i in stuff:
  2. ...     if i > 10:
  3. ...         print i
  4. ...         
  5. 45.53
  6. 6.41
  7. 21.76
  8. 12.19
  9. 1.47
  10.  
So I tried this:
Expand|Select|Wrap|Line Numbers
  1. >>> newints = int(stuff)
  2. Traceback (most recent call last):
  3.   File "<interactive input>", line 1, in <module>
  4. TypeError: int() argument must be a string or a number, not 'list'
  5.  

So if I need to convert the elements to integers...how could I do that?

Same question if I already had thigns in a dictionary, say

dd = {'damon': '5', 'cano' : '8', 'abreu' : '23', 'arod' : '49'}

thanks
Aug 15 '07 #1
Share this Question
Share on Google+
2 Replies

bartonc
Expert 5K+
P: 6,596
I think the elements in my list must not be being read as integers because when I do something like
Expand|Select|Wrap|Line Numbers
  1. >>> for i in stuff:
  2. ...     if i > 10:
  3. ...         print i
  4. ...         
  5. 45.53
  6. 6.41
  7. 21.76
  8. 12.19
  9. 1.47
  10.  
So I tried this:
Expand|Select|Wrap|Line Numbers
  1. >>> newints = int(stuff)
  2. Traceback (most recent call last):
  3.   File "<interactive input>", line 1, in <module>
  4. TypeError: int() argument must be a string or a number, not 'list'
  5.  

So if I need to convert the elements to integers...how could I do that?

Same question if I already had thigns in a dictionary, say

dd = {'damon': '5', 'cano' : '8', 'abreu' : '23', 'arod' : '49'}

thanks
Expand|Select|Wrap|Line Numbers
  1. >>> dd = {'damon': '5', 'cano' : '8', 'abreu' : '23', 'arod' : '49'}
  2. >>> for key, value in dd.items():
  3. ...     dd[key] = int(value)
  4. ...     
  5. >>> dd
  6. {'damon': 5, 'cano': 8, 'abreu': 23, 'arod': 49}
  7. >>> 
Aug 15 '07 #2

bvdet
Expert Mod 2.5K+
P: 2,851
For a list:
Expand|Select|Wrap|Line Numbers
  1. >>> alist = [12.1, 25.6, 33.9]
  2. >>> alist = [int(r) for r in alist]
  3. >>> alist
  4. [12, 25, 33]
  5. >>> 
Aug 16 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.