유용한 Python 내장함수 (3)

idle-danie·2023년 3월 24일
2
post-thumbnail

Python 내장함수, 자료형, 정규표현식, 모듈...etc


enumerate(list): 원소와 인덱스 동시에 얻을 수 있는 함수

for i, element in enumerate(a, start = 1):
	print(i, element)

1 daniel
2 john
3 alex

zip(): iterator 객체 사용하여 병렬처리 가능

>>> name = ["Daniel", "Alex", "Steve"]
>>> st_num = [101, 102, 103]
>>> st_score = [100, 90, 34]
>>> st_score.append(12)
exam_score = list(zip(name, st_num, st_score))
>>> exam_score
[('Daniel', 101, 100), ('Alex', 102, 90), ('Steve', 103, 34)]

>>> a, b, c = zip(*exam_score)
>>> a, b, c
(('Daniel', 'Alex', 'Steve'), (101, 102, 103), (100, 90, 34))
>>> exam_score
[('Daniel', 101, 100), ('Alex', 102, 90), ('Steve', 103, 34)]

>>> dict(zip(name, st_num))
{'Daniel': 101, 'Alex': 102, 'Steve': 103}

>>> for i in zip(name, st_num):
	print(i[0], i[1])

Daniel 101
Alex 102
Steve 103

from collections import Counter: 딕셔너리 형의 객체를 반환하여 요소의 개수를 value로 확인할 수 있다. most_common()은 tuple이 포함된 리스트를 반환한다.

>>> from collections import Counter
>>> counter = Counter() # 빈 카운터 생성

>>> Counter(name)
Counter({'Daniel': 1, 'Alex': 1, 'Steve': 1})
>>> Counter("sdifjodvmef")
Counter({'d': 2, 'f': 2, 's': 1, 'i': 1, 'j': 1, 'o': 1, 'v': 1, 'm': 1, 'e': 1})

>>> a = Counter(name)
>>> a["Daniel"]
1

>>> Counter("doijfoivmkd").most_common()
[('d', 2), ('o', 2), ('i', 2), ('j', 1), ('f', 1), ('v', 1), ('m', 1), ('k', 1)]
>>> Counter("udsinjckwdckomvl").most_common(3)
[('d', 2), ('c', 2), ('k', 2)]

>>> b = Counter([1,1,1,1,1,1,1,1,2,2,2,12,31])
>>> a+b
Counter({1: 13, 2: 8, 21: 1, 12: 1, 31: 1})
>>> a-b
Counter({2: 2, 21: 1})
>>> a=b.total()
Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    a=b.total()
AttributeError: 'Counter' object has no attribute 'total'
파이썬 3.1이후에 total()이 추가되었다고 하는데 지금은 호출되지 않는다. 굳이 구하려 한다면 아래와 같이 구하면 될 것이다. 
>>> sum(a.values())
11

>>> a & b
Counter({1: 5, 2: 3})
>>> a | b
Counter({1: 8, 2: 5, 21: 1, 12: 1, 31: 1})
>>> a.items()
dict_items([(1, 5), (2, 5), (21, 1)])
>>> a.values()
dict_values([5, 5, 1])

>>> list(a.elements())
[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 21]

>>> a.update([1,1,1,1,1,1,1])
>>> a
Counter({1: 12, 2: 5, 21: 1})

>>> a.subtract([2,2,2,2])
>>> 
>>> a
Counter({1: 12, 2: 1, 21: 1})

sorted의 key활용: 다중조건에서 오름차순을 사용할 때 str같은 경우 -를 이용할 때 bad operand type으로 취급된다.

>>> sorted(array, key = lambda x:(x[1], x[0]))
[('b', 2), ('g', 3), ('a', 4), ('k', 4), ('f', 5)]
>>> sorted(array, key = lambda x:(-x[1], x[0]))
[('f', 5), ('a', 4), ('k', 4), ('g', 3), ('b', 2)]

dic 정렬: lamda식을 이용하여 key, value를 기준으로 정렬

- key 정렬

>>> sorted(dic)
['a', 'b', 'f', 'g', 'k']
>>> sorted(dic.items())
[('a', 4), ('b', 2), ('f', 5), ('g', 3), ('k', 4)]
>>> dict(sorted(dic.items()))
{'a': 4, 'b': 2, 'f': 5, 'g': 3, 'k': 4}

- value 정렬

>>> sorted(dic,key=lambda x:dic[x])
['b', 'g', 'a', 'k', 'f']
>>> sorted(dic.items(), key=lambda x:x[1])
[('b', 2), ('g', 3), ('a', 4), ('k', 4), ('f', 5)]
>>> dict(sorted(dic.items(), key=lambda x:x[1]))
{'b': 2, 'g': 3, 'a': 4, 'k': 4, 'f': 5}

startswith(): 특정 문자열로 시작되는지 확인하는 함수

>>> string = "helloworld"
>>> string.startswith("hello")
True
>>> string.startswith("hello ")
False
>>> string = "Hello, my name is Daniel"

>>> for voc in string.lower().split():
	if voc.startswith("daniel"):
		print("there is Daniel!")

there is Daniel!

lower(), upper(), islower(), isupper(), swapcase(), capitalize()

>>> string
'Hello, my name is Daniel'

>>> string.swapcase()
'hELLO, MY NAME IS dANIEL'

>>> "dddd".capitalize()
'Dddd'

>>> string.upper()
'HELLO, MY NAME IS DANIEL'

>>> string.lower()
'hello, my name is daniel'

>>> string.isupper()
False
>>> string.islower()
False
>>> string.lower().islower()
True

>>> string[10:].upper()
'NAME IS DANIEL'
>>> string = string[0:10] + string[10:].upper()
>>> string
'Hello, my NAME IS DANIEL'
>>> 

set() 연산

  • 집합 선언
>>> s1 = {1,2,3,4,5}
>>> s2 = {3,4,5,6,7}
>>> a = [1,2]
>>> s3 = set(a)
>>> s3
{1, 2}
  • 합집합 (s.union())
>>> s4 = s1 | s2
>>> s4
{1, 2, 3, 4, 5, 6, 7}
  • 교집합 (s.intersection())
>>> s5 = s1 & s2
>>> s5
{3, 4, 5}
  • 차집합 (s.difference())
>>> s2-s1
{6, 7}
  • 집합간의 비교, 교집합이 공집합인지 여부는 s.isdisjoint()
>>> s1 == s2
False
>>> s1 != s2
True
>>> s2
{3, 4, 5, 6, 7}
>>> s1 = {3}
>>> s1.isdisjoint(s2)
False
  • add(), update()
>>> s1.add(9)
>>> s1
{1, 2, 3, 4, 5, 9}
>>> s1.update({1,2,4,5})
>>> s1
{1, 2, 3, 4, 5, 9}
  • remove(), discard(), pop(): discard()는 제거할 원소가 없어도 에러X
>>> s1.remove(1)
>>> s1
{2, 3, 4, 5, 9}
>>> s1.discard(10)
>>> s1.discard(3)
>>> s1
{2, 4, 5, 9}
  • pop(), clear()
>>> s1.pop()
2
>>> s1
{4, 5, 9}
>>> s1.clear()
>>> s1
set()

참고문헌
1. https://docs.python.org/3/library/collections.html#collections.Counter
2. https://docs.python.org/3/tutorial/index.html
3. https://blockdmask.tistory.com/451

profile
wanna be idéal DE

0개의 댓글

관련 채용 정보