Python & Automation

Python Strudy - day 5

모모토 2022. 1. 31. 01:41
반응형
자동화를 위한 Python 공부 5일차


시퀀스 자료형 - list 2

 

산술 내장 함수

  1. sum() : list에 대한 합계 계산
  2. max() : list에 대한 최소값 계산
  3. min() : list에 대한 최소값 계산
  4. abs() : 절대값 계산
  5. round() : 소수점 이하 자릿수 결정
#list 산술 내장함수 원리 구현
A = [ 32.515, 62.718, 82.638, 71.376, -53.995 ]

print( f'l = {A} ( {len( A )} )' )

max_number = A[0]
min_number = A[0]
total = 0

for i in A:
  if i > max_number:
    max_number = i
  if i < min_number:
    min_number = i
  total += i

print(f'max_number is {max_number} , min_number is {min_number} , total = {total}')

#list 내장 함수

print(f'max number is {max(A)} , min number is {min(A)} , sum is {sum(A)} ')
print(f'-53.995의 절대값 : {abs(A[4])}')
print(f'32.515 반올림 default -> {round(A[0])}')
print(f'32.515 소수점 자릿수 1자리 제한 -> {round(A[0] , 1 )}')

>>>
l = [32.515, 62.718, 82.638, 71.376, -53.995] ( 5 )
max_number is 82.638 , min_number is -53.995 , total = 195.252
max number is 82.638 , min number is -53.995 , sum is 195.252 
-53.995의 절대값 : 53.995
32.515 반올림 default -> 33
32.515 소수점 자릿수 1자리 제한 -> 32.5

 

list 의 복사

 

list 복사 -> list 자체를 복사하는가 아니면 reference 참조를 복사하는가

  1. list는 내부적으로 reference를 이용하여 관리한다.
  2. list를 단순하게 복사하면 reference만 복사된다. 따라서 복사본에서 변경한 내용은 원본에도 영향을 미친다. 만약 더 알고싶다면 자바를 공부할 때 만든 게시물 >> Click (Call by Value)  << 을 참고해보자
  3. list 의 내용을 복사하려면 별도의 내장 함수( copy() )를 이용하여 복사를 수행해야 한다. 따라서 copy를 import 하여 모듈을 로드하는 명령어를 사용해야 함 , 이는 코드를 참조하면 이해가 빠르다.
#list 복사 -> list 자체를 복사하는가 아니면 reference 참조를 복사하는가

list = [1,2,3,4,5,6,7]
list_copy = list
print(f'{list_copy} \n list_copy\'s id : {id(list_copy)} , list\'s id : {id(list)}')

import copy #copy 함수를 가진 모듈을 로드
list_copy2 = copy.copy(list) #새로운 영역에 list를 복사
print(f'{list_copy2} \n list_copy\'s id : {id(list_copy2)} , list\'s id : {id(list)}')


>>>
[1, 2, 3, 4, 5, 6, 7] 
 list_copy's id : 140489180825712 , list's id : 140489180825712
[1, 2, 3, 4, 5, 6, 7] 
 list_copy's id : 140489180980560 , list's id : 140489180825712

 

list comprehension 

 

list comprehension이 도대체 무슨뜻일까 구글에 검색해보면 다음과 같다

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.

쉽게 말해서 리스트를 만드는 간단한 코드를 짜는 문법이라고 생각하자

 

문법은 다음과 같다

 

변수 = [값 for 값 in 반복식]
변수 = [값 for 값 in 반복식 if 조건식]

 

#일반적인 for 문으로 list 생성하기
list = []

for i in range(2 , 101 , 2):
  list.append(i)

print(list)

>>>
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]


#list comprehension

list2 = [i for i in range(1,101) if i % 2 ==0]
print(list2)

>>>
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]


list3 = [i*2 for i in range(1,101) if i % 2 ==0]
print(list3)

>>>
[4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 148, 152, 156, 160, 164, 168, 172, 176, 180, 184, 188, 192, 196, 200]

 

 

마지막으로 다음에 포스팅할 dict를 배우기 전 list로 검색프로그램을 구현해보자

 

#list를 이용한 검색 프로그램 구현

data = [ 5, 10, 1, 2, 4, 7, 6, 8, 9, 3 ]
search_key = int(float(input('검색어를 입력하시오 (종료:-1)')))

while search_key != -1:
  count = data.count(search_key)
  if count == 0:
    search_OK = False
  else:
    search_OK = True
    position = data.index(search_key)

  if search_OK:
    print(f'{search_key}의 index : {position}')
  else:
    print( f'Error : {search_key}값은 없음!!!' )
  search_key = int( float( input( '검색어 입력 ( 종료 : -1 ): ' ) ) )


>>>
검색어를 입력하시오 (종료:-1)5
5의 index : 0
검색어 입력 ( 종료 : -1 ): 4
4의 index : 4
검색어 입력 ( 종료 : -1 ): -1

'Python & Automation' 카테고리의 다른 글

[Ansible] 환경 구성 자동화를 위한 Ansible  (0) 2022.02.14
Python Study - day 6  (0) 2022.02.01
Python Study - day 4  (0) 2022.01.27
Python Study - day 3  (0) 2022.01.27
Python study - day 2  (0) 2022.01.26