개발/Python

[Python] - Powerful Function

Dortmoot 2022. 7. 27. 14:12

1. Range


  • range는 range(start, end, step) Option
  • range's result  start_number ~ end-1 collection
list(range(5,10))
> [5, 6, 7, 8, 9]
list(range(10,20,2))
> [10, 12, 14, 16, 18]

 

2. Enumerate


  • Use repeat Loop we need to check times Loop
  • return tuple( index , element )
for i, v in enumerate(t):
    print("index : {}, value: {}".format(i,v))
"""
index : 0, value: 1
index : 1, value: 5
index : 2, value: 7
index : 3, value: 33
index : 4, value: 39
index : 5, value: 52
"""

 

3. Map


map(function, iterable)

 

  • map is function that processes the elements of a list as a specified function
  • map do not change origin list and create new list
# change float to int
a = [1.2, 2.5, 3.7, 4.6]
a = [int(i) for i in a ]

# map function
a = list(map(int,a))

# int+1
list(map(lambda x:int(x)+1 , a))

 

4. Filter


filter(function, iterable)
  • filter function return Elements filtered under certain conditions to iterator object
a = [1,2,3,4]
# filter function
result = list(filter(lambda x : x%2==0 , a))

 

5. Zip


  • zip function get parameter iterable object and returns iterator that can sequentially access each iterable object element 
  • Iterate over several iterables in parallel, producing tuples with an item from each one.
  • you should be aware of iterable element length. ( the data is woven based on the shortest argument, and the rest is discarded )
numbers = [1, 2, 3]
letters = ["A", "B", "C"]
[pair for pair in zip(numbers, letters) ]
> [(1, 'A'), (2, 'B'), (3, 'C')]

#dict example
keys = [1, 2, 3]
values = ["A", "B", "C"]
dict(zip(keys, values))

# be careful
numbers = ["1", "2", "3"]
letters = ["A"]
list(zip(numbers, letters))
> [('1', 'A')]

 

6. Divmod


q, r = divmod(n, d)
q, r = (n // d, n % d)