Python Code Snippets

List Comprehension


3 parts to a list comp
(not all 3 may be there)

1. The loop
- identify the 'control variable' and the list
- eg. for i in mylist

2. Transformation
-modifies the control variable and returns the modified value
- eg. i *2

3. Filtering
- select elements to be processed into the new list
- eg. if i > 5

Demonstration

mylist = [1,2,3,4]

modlist = []
for i in mylist:
    if i >5:
        j = i*2
        modlist.append(j)

##

modlist = [i*2 for in in mylist if i > 5]
lines = [ln.rstrip() for ln in open('myfile.txt') if not ln.startswith('#')]

mydict = {'a' : 10000, 'b': 20000, 'c':30000, 'd':40000}
valid_keys = mydict.items()
underpaid_ids = [id for (id, salary) in mydict.items() if salary < 25000]

[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

vec = [-4, -2, 0, 2, 4]
# create a new list with the values doubled
[x*2 for x in vec]

# filter the list to exclude negative numbers
[x for x in vec if x >= 0]

# apply a function to all the elements
[abs(x) for x in vec]

# call a method on each element
freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
[weapon.strip() for weapon in freshfruit]

# create a list of 2-tuples like (number, square)
[(x, x**2) for x in range(6)]

# the tuple must be parenthesized, otherwise an error is raised
[x, x**2 for x in range(6)]
  File "", line 1
    [x, x**2 for x in range(6)]
               ^
SyntaxError: invalid syntax
# flatten a list using a listcomp with two 'for'
vec = [[1,2,3], [4,5,6], [7,8,9]]
[num for elem in vec for num in elem]

[[row[i] for row in matrix] for i in range(4)]

see --> zip(*matrix) -->built in function

No comments: