Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

10 - Useful Functions

Uploaded by

fersd2018
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

10 - Useful Functions

Uploaded by

fersd2018
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

10.

Useful functions
This section discusses the following functions:
• print
• range
• sorted
• enumerate
• zip
• all_any
• lambda
• map
• filter

print
Function print has been used many times, but its full syntax has not yet been discussed:
print(*items, sep=' ', end='\n', file=sys.stdout, flush=False)

Function print outputs all elements by separating them by their sep value and finishes
output with end value.

sep
Parameter sep controls which separator will be used between elements. By default, space
is used. You can change sep value to any other string:
print(1, 2, 3, sep='|') # 1|2|3
print(1, 2, 3, sep=f"\n{'-' * 10}\n")
'''
1
----------
2
----------
3
'''

items = [1, 2, 3, 4, 5]
print(*items, sep=', ') # 1, 2, 3, 4, 5

58
end
Parameter end controls which value will be displayed after all elements are printed. By
default, new line character is used. You can change end value to any other string:
print(1, 2, 3, end='\n' + '-' * 10)
'''
1 2 3
----------
'''

file
Parameter file controls where values of print function are displayed. The default
output is sys.stdout.

Python allows to pass to file as an argument any object with write(string) method.
f = open('result.txt', 'w')
for num in range(10):
print('Item {}'.format(num), file=f)

f.close()

cat result.txt # Item 0 … Item 9

range
Function range returns an immutable sequence of numbers as a range object. Function
syntax:
range(stop)
range(start, stop[, step])

Parameters of function:
• start - from what number the sequence begins. By default - 0
• stop - on which number the sequence of numbers ends. Mentioned number is not
included in range
• step - with what step numbers increase. By default

In order to indicate sequence step, you have to pass three arguments:


list(range(0, 10, 2)) # [0, 2, 4, 6, 8]

59
Function range can also generate descending sequences of numbers:
list(range(10, 0, -1)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
list(range(10, 0, -2)) # [10, 8, 6, 4, 2]

The range object supports all operations that support sequences in Python, except
addition and multiplication.
nums = range(5) # range(0, 5)
3 in nums # True
nums[0] # 0
nums[-1] # 4
# Range supports slices:
nums[1:] # range(1, 5)
nums[:3] # range(0, 3)
len(nums) # 5
min(nums) # 0
max(nums) # 4

sorted
Function sorted returns a new sorted list that is obtained from an iterable object that has
been passed as an argument. Function also supports additional options that allow you to
control sorting.

The first aspect that is important to pay attention to - sorted returns a list. If you sort a list
of items, a new list is returned:
list_of_words = ['one', 'two', 'list', '', 'dict']

sorted(list_of_words) # ['', 'dict', 'list', 'one', 'two']

When sorting a tuple also a list returns:


tuple_of_words = ('one', 'two', 'list', '', 'dict')

sorted(tuple_of_words) # ['', 'dict', 'list', 'one', 'two']

60
If you pass a dictionary to sorted the function will return sorted list of keys:
dict_for_sort = {
'id': 1,
'name': 'London',
'it_vlan': 320,,
'mngmt_vlan': 99,
'port': 'G1/0/11'
}

sorted(dict_for_sort)
'''
['id',
'it_vlan',
'mngmt_vlan',
'name',
'port',]
'''

reverse
The reverse flag allows you to control the sorting order. By default, sorting will be in
ascending order of items:
list_of_words = ['one', 'two', 'list', '', 'dict']

sorted(list_of_words)
# ['', 'dict', 'list', 'one', 'two']

sorted(list_of_words, reverse=True)
# ['two', 'one', 'list', 'dict', '']

key
With key option you can specify how to perform sorting. The key parameter expects
function by which the comparison should be performed.

For example you can sort a list of strings by string length:


list_of_words = ['one', 'two', 'list', '', 'dict']

sorted(list_of_words, key=len)
# ['', 'one', 'two', 'list', 'dict']

The key option can accept any functions, not only embedded ones. It is also convenient to
use anonymous lambda() function.

61
enumerate
Sometimes, when iterating objects in for loop, it is necessary not only to get object itself
but also its sequence number. This can be done by creating an additional variable that will
increase by one with each iteration. However, it is much more convenient to do this with
iterator enumerate.

Basic example:
list1 = ['str1', 'str2', 'str3']

for position, string in enumerate(list1):


print(position, string)
'''
0 str1
1 str2
2 str3
'''

enumerate can count not only from scratch but from any value that has been given to it
after object:
list1 = ['str1', 'str2', 'str3']

for position, string in enumerate(list1):


print(position, string)
'''
100 str1
101 str2
102 str3
'''

list(enumerate(list1, 100))
# [(100, 'str1'), (101, 'str2'), (102, 'str3')]

62
zip
zip function:
• sequences are passed to function
• zip returns an iterator with tuples in which n-tuple consists of n-elements of
sequences that have been passed as arguments
• for example, 10th tuple will contain 10th element of each of passed sequences
• if sequences with different lengths have been passed to input, they will all be cut
by the shortest sequence
• the order of elements is respected

Note: Since zip is an iterator, list is used to show its contents

Example of using zip:


a = [1, 2, 3]
b = [100, 200, 300]
list(zip(a, b)) # [(1, 100), (2, 200), (3, 300)]

Use zip with lists of different lengths:


a = [1, 2, 3, 4, 5]
b = [10, 20, 30, 40, 50]
c = [100, 200, 300]

list(zip(a, b, c))
# [(1, 10, 100), (2, 20, 200), (3, 30, 300)]

Using zip to create a dictionary


Example of using zip to create a dictionary:
d_keys = ['hostname', 'location', 'vendor', 'model', 'IOS', 'IP']
d_values = ['london_r1', '21 New Globe Walk', 'Cisco', '4451',
'15.4', '10.255.0.1']

r1 = dict(zip(d_keys, d_values))
print(r1)
'''
{'IOS': '15.4',
'IP': '10.255.0.1',
'hostname': 'london_r1',
'location': '21 New Globe Walk',
'model': '4451',
'vendor': 'Cisco'}
'''

63
In example below there is a separate list which stores keys and a dictionary which stores
information about each device in form of list (to preserve order).

Collect them in dictionary with keys from list and information from dictionary data:
d_keys = ['hostname', 'location', 'vendor', 'model', 'IOS', 'IP']
data = {
'r1': ['london_r1', '21 New Globe Walk', 'Cisco', '4451',
'15.4', '10.255.0.1'],
'r2': ['london_r2', '21 New Globe Walk', 'Cisco', '4451',
'15.4', '10.255.0.2'],
'sw1': ['london_sw1', '21 New Globe Walk', 'Cisco', '3850',
'3.6.XE', '10.255.0.101']
}

london_co = {}
for k in data.keys():
london_co[k] = dict(zip(d_keys, data[k]))

print(london_co)

all
Function all returns True if all elements are true (or object is empty).
all([False, True, True]) # False

For example, it is possible to check that all octets in an IP address are numbers:
ip = '10.0.1.1'

all([i.isdigit() for i in ip.split('.')]) # True

any
Function any returns True if at least one element is true.
any([i.isdigit() for i in '10.1.1.a'.split('.')]) # True

64
Anonymous function (lambda expression)
In Python, lambda expression allows creation of anonymous functions - functions that are
not tied to a name.

Anonymous function:
• may contain only one expression
• can pass as many arguments as you want

Standard function:
def sum_arg(a, b): return a + b

Similar anonymous function or lambda function:


sum_arg = lambda a, b: a + b
sum_arg(1, 2) # 3

Note that there is no return operator in lambda function definition because there can only
be one expression in this function that always returns a value and closes the function.

Function lambda is convenient to use in expressions where you need to write a small
function for data processing. For example, in sorted function you can use lambda
expression to specify sorting key:
list_of_tuples = [('IT_VLAN', 320),
('Mngmt_VLAN', 99),
('User_VLAN', 1010),
('DB_VLAN', 11)]

sorted(list_of_tuples, key=lambda x: x[1])


# [('DB_VLAN', 11), ('Mngmt_VLAN', 99), ('IT_VLAN', 320),
('User_VLAN', 1010)]

Function lambda is also useful in map and filter functions which will be discussed in
the following sections.

65
map
Function map applies function to each element of sequence and returns iterator with
result.

For example, map can be used to perform element transformations. Convert all strings to
uppercase:
list_of_words = ['one', 'two', 'list', '', 'dict']

map(str.upper, list_of_words) # <map at 0xb45eb7ec>

list(map(str.upper, list_of_words))
# ['ONE', 'TWO', 'LIST', '', 'DICT']

Converting to numbers:
list_of_str = ['1', '2', '5', '10']

list(map(int, list_of_str)) # [1, 2, 5, 10]

With map it is convenient to use lambda expressions:


vlans = [100, 110, 150, 200, 201, 202]

list(map(lambda x: 'vlan {}'.format(x), vlans))


'''
['vlan 100', 'vlan 110', 'vlan 150', 'vlan 200', 'vlan 201', 'vlan
202']
'''

If map function expects two arguments, two lists are passed:


nums = [1, 2, 3, 4, 5]
nums2 = [100, 200, 300, 400, 500]

list(map(lambda x, y: x*y, nums, nums2))


# [100, 400, 900, 1600, 2500]

List comprehension instead of map


As a rule, you can use list comprehension instead of map. The list comprehension option
is often clearer, and in some cases even faster.
But map can be more effective when you have to generate a large number of elements
because map is an iterator and list comprehension generates a list.

Examples similar to those above in list comprehension version.

66
Convert all strings to uppercase:
list_of_words = ['one', 'two', 'list', '', 'dict']
[str.upper(word) for word in list_of_words]
# ['ONE', 'TWO', 'LIST', '', 'DICT']

String formatting:
vlans = [100, 110, 150, 200, 201, 202]
['vlan {}'.format(x) for x in vlans]
# ['vlan 100', 'vlan 110', 'vlan 150', 'vlan 200', 'vlan 201',
'vlan 202']

Use zip to get pairs of elements:


nums = [1, 2, 3, 4, 5]
nums2 = [100, 200, 300, 400, 500]

[x * y for x, y in zip(nums, nums2)]


# [100, 400, 900, 1600, 2500]

filter
Function filter() applies function to all sequence elements and returns an iterator with
those objects for which function has returned True.

For example, return only those strings that contain numbers:


list_of_strings = ['one', 'two', 'list', '', 'dict', '100', '1', '50']

fAs a rule, you can use list comprehension instead of filter. Examples
similar to those above in list comprehension version. Return only those
strings that contain numbers:ter(str.isdigit, list_of_strings)
# <filter at 0xb45eb1cc>
list(filter(str.isdigit, list_of_strings))
# ['100', '1', '50']

From the list of numbers leave only odd:


list(filter(lambda x: x % 2, [10, 111, 102, 213, 314, 515]))
# [111, 213, 515]

67
List comprehension instead of filter
As a rule, you can use list comprehension instead of filter.
Examples similar to those above in list comprehension version.

Return only those strings that contain numbers:


list_of_strings = ['one', 'two', 'list', '', 'dict', '100', '1', '50']

[s for s in list_of_strings if s.isdigit()]


# ['100', '1', '50']

Odd/even numbers:
nums = [10, 111, 102, 213, 314, 515]

[n for n in nums if n % 2] # [111, 213, 515]


[n for n in nums if not n % 2] # [10, 102, 314]

68

You might also like