## Pages

Showing posts with label list comprehension. Show all posts
Showing posts with label list comprehension. Show all posts

## Saturday, May 16, 2009

### How to sum the values of a Python dictionary

Suppose that we have a Python dictionary,
x = {'a': 3, 'b': 2, 'c':7}

and, we want to add the values i.e. 3 + 2 + 7 = 12.

Here are the three ways to add the values.

### Using list comprehension

>>> x = {'a': 3, 'b': 2, 'c':7}
>>> sum([i for i in x.values()])
12

### Using for loop I

>>> x = {'a': 34, 'b': 2, 'c':7}
>>> total = 0
>>> for i in x.values():
total += i

### Using for loop II

>>> x = {'a': 34, 'b': 2, 'c':7}
>>> total = 0
>>> for key in x.keys():
total += x[key]

## Wednesday, May 13, 2009

### Strings to integer

To convert a string to an integer:
>>> x = '1234'
>>> int(x)
1234

### Strings to float

To convert a string to float:
>>> x = '1234'
>>> float(x)
1234.0

>>> y = '1234.678'
>>> float(y)
1234.6780000000001
but, convertion of '1234.678' to integer using int() will gives an error.
>>> int(y)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
int(y)
ValueError: invalid literal for int() with base 10: '1234.678'
A workaround is by first converting to float, then to integer:
>>> y = '1234.678'
>>> int(float(y))
1234

### List/tuple of strings to list of integers

1. Using list comprehension
>>> x = ['07', '11', '13', '14', '28']
>>> [int(i) for i in x]
[7, 11, 13, 14, 28]
2. Using map
>>> x = ['07', '11', '13', '14', '28']
>>> list(map(int, x))
[7, 11, 13, 14, 28]
Mix of integers and floats
>>> x = ['7.424124', '11', '13.423', '14.53453656', '28.2']
>>> list(map(int, map(float, x)))
[7, 11, 13, 14, 28]

### List/tuple of strings to list of floats

1. Using list comprehension
>>> x = ['7.424124', '1', '13.423', '14.53453656', '28.2']
>>> [float(i) for i in x]
[7.4241239999999999, 1.0, 13.423,
14.534536559999999, 28.199999999999999]
2. Using map
>>> x = ['7.424124', '1', '13.423', '14.53453656', '28.2']
>>> list(map(float, x))
[7.4241239999999999, 1.0, 13.423,
14.534536559999999, 28.199999999999999]