Python tips

yozzum·2022년 3월 23일
0

1. map

  • syntax: map(function, iterable)

You can use a for loop to apply something to all elements in a list.

a = [1.2, 2.5, 3.7, 4.6]
for i in range(len(a)):
    a[i] = int(a[i])
print(a)
# output: [1,2,3,4]

You can do exactly the same by using map. This is shorter and faster.

a = [1.2, 2.5, 3.7, 4.6]
a = list(map(int, a))
print(a)
# output: [1,2,3,4]

2. *args

  • args stands for arguments
  • takes multiple arguments as elements of a tuple.
def myFunc(*args):
    print(args)
myFunc(10, 20, 'a')
# output: (10, 20, 'a')
  • If you want to pass a list and recieve it as a tuple, add an '*' in front of the list variable.
def myFunc(*args):
    print(args)

lst = [10, 20, 'a']
myFunc(*lst)

3. **kwargs

  • kwargs stands for keyword arguments
  • takes 'x=y' form of arguments as a dictionary.
def myFunc(*args, **kwargs):
    print(args)
    print(kwargs)
myFunc(10, 20,'a', x=100, y=200, z='b')
# output: (10, 20, 'a')
#         {'x': 100, 'y': 200, 'z': 'b'}
def myFunc(*args, **kwargs):
     print(args)
     print(kwargs)
p1 = [10, 20, 'a']
myFunc(*p1,x=100, y=200, z='b')
# output: (10, 20, 'a')
#         {'x': 100, 'y': 200, 'z': 'b'}

4. enumerate

  • list에서 index와 value 둘 다 활용하고 싶을 때 사용한다.
  • value에 대한 순위를 뽑고 싶을 때 cnt 등을 활용하지 않고 index를 활용하면 훨씬 효율적이다.
lst = [10,20,30]
for idx, val in enumerate(lst):
	print(idx, val)
profile
yozzum

0개의 댓글