Language/Python

231115 Python_for문, range()

잇꼬 2023. 11. 20. 18:32
728x90
반응형
SMALL

for문 
- 리스트, 튜플, 집합, 딕셔러니, 문자열의 첫번째 값 부터 마지막 값까지 순서대로 카운터 변수에 입력해서 반복해서 수행한다.
for 카운터 변수 in (리스트, 튜플, 집합, 딕셔러니, 문자열):
반복수행할 문장

x = ['sql', 'plsql', 'python']

for i in x:
    print(i)

for i in 'python':
    print(i)
    
x = [(1,2),(3,4),(5,6)]

for i in x:
    print(i)

 

# 튜플 각각 출력

for i, j in x:
    print(i, j)

 

# 덧셈

for i, j in x:
    print(i+j)

 

# 로직 확인(덧셈)

x[0][0] + x[0][1]

 

# while문 -> for문 으로 변경

score = [90, 55, 63, 78, 80]
for i in score:
    if i >= 60:
        print('점수 : {} => 합격'.format(i))
    else:
        print('점수 : {} => 불합격'.format(i))

x = [1,2,3,4,5]

for i in x:
    print(i)

 

range(시작, 끝(미만), 증가분) 

range(1,101,1)
list(range(1,101,1))

for i in range(1,11,1):
    print(i)

for i in list(range(1,11,1)):
    print(i)

 

# fruits 변수에 있는 값 중에 유일한 값만 fruits_unique 변수에 입력

fruits_unique = []  # 유일한 과일이름 저장
for i in fruits:
    if i not in fruits_unique:
        fruits_unique.append(i)

fruits_unique    

for i in ['사과', '오렌지']:
    print('{} : {}'.format(i, fruits.count(i)))

for i in fruits_unique:
    print('{} : {}'.format(i,fruits.count(i)))

for i in set(fruits):
    print('{} : {}'.format(i,fruits.count(i)))

fruits = ["사과", "오렌지", "배", "귤", "포도", "바나나", "키위", "딸기", "망고", 
          "사과", "오렌지", "배", "귤", "포도", "바나나", "키위", "딸기", "망고", 
          "사과", "오렌지", "배", "귤", "포도", "바나나", "키위", "딸기", "블루베리", 
          "사과", "오렌지", "배", "포도", "바나나", "키위", "딸기", "파인애플" ]

fruits_dict = {} # key, value 변수 지정
fruits_dict

 

# 1. 만약에 '사과' fruits_dict 키가 없으면 fruits_dict[사과] = 1 등록
    # '사과' not in fruits_dict.keys()

fruits_dict['사과'] = 1
fruits_dict

# 2. 만약에 '사과' fruits_dict key가 있으면, 
    # '사과' in fruits_dict.keys() -> fruits_dict['사과'] + 1 = fruits_dict['사과'] 등록

fruits_dict['사과'] = fruits_dict['사과'] + 1
fruits_dict

'사과' in fruits_dict
'사과' in fruits_dict.keys()

 

<<방법1>>

# 변수명.keys() , 정렬 X

fruits_dict = {}
fruits_dict

for i in fruits:
    if i not in fruits_dict.keys(): #1
        fruits_dict[i] = 1
    else:
        fruits_dict[i] = fruits_dict[i] + 1 #2

fruits_dict

 

<<방법2>>

# set()

fruits_dict = {}
fruits_dict # 과일명만 등록

for key in set(fruits):
    fruits_dict[key] = 0

fruits_dict

for i in fruits:
    fruits_dict[i] = fruits_dict[i] + 1

fruits_dict

 

<<방법3>>

변수명.get()

fruits_dict['사과']
fruits_dict.get('사과')

fruits_dict['감'] # 없으면 오류
fruits_dict.get('감') # 없으면 리턴x
fruits_dict.get('감', 0) # 없으면 0으로 리턴

fruits_dict.get('사과', 0)

fruits_dict = {}
fruits_dict

for i in fruits:
    p = fruits_dict.get(i, 0) # 있으면 value(카운터), 없으면 0 리턴
    fruits_dict[i]  = p + 1 # 카운터 증가

fruits_dict

 

<<방법4>>

import collections

fruits_dict = collections.defaultdict(int) # = (p = fruits_dict.get(i, 0)) 변수를 선언했을 경우, 동일한 기능이다
fruits_dict

for i in fruits:
    fruits_dict[i] = fruits_dict[i] + 1

fruits_dict

 

<<방법5>>

# 자동 정렬

import collections

fruits_dict = collections.Counter(fruits) # <<방법1>> 이 내부적으로 돌아가는중;;

fruits_dict.items()
fruits_dict.keys()
fruits_dict.values()

fruits_dict
type(fruits_dict)

 

# 딕션러리 변수에 키, 값을 정렬

type(fruits_dict)

sorted(fruits_dict) # key 순으로 
sorted(fruits_dict.keys())
sorted(fruits_dict.values())
sorted(fruits_dict.items()) # key를 기준으로 오름차순 정렬
sorted(fruits_dict.items(), reverse=True) # key를 기준으로 내름차순 정렬

 

# key 기준으로 정렬, 오름차순 정렬

for key, value in sorted(fruits_dict.items()):
    print(key, value)

 

# 내림차순

for key, value in sorted(fruits_dict.items(), reverse=True):
    print(key, value)

 

# operator.itemgetter(0) : key 기준 = SQL's ORDER BY절, 위치지정방식
# operator.itemgetter(1) : value 기준
# key 기준으로 정렬, 오름차순 정렬

import operator

for key, value in sorted(fruits_dict.items(), key=operator.itemgetter(0)):
    print(key, value)

 

# 내림차순

for key, value in sorted(fruits_dict.items(), reverse=True, key=operator.itemgetter(0)):
    print(key, value)


# fruits_dict.items() 으로 하되, values 기준으로 오름차순 정렬
# 값을 기준으로 오름차순 정렬

for key, value in sorted(fruits_dict.items(), key=operator.itemgetter(1)):
    print(key, value)

 

# 값을 기준으로 오름차순 정렬

for key, value in sorted(fruits_dict.items(), key=operator.itemgetter(1), reverse=True):
    print(key, value)

 

# for문을 한줄로 처리

y = []

for i in range(1,11,1):
    y.append(i * 2)

y

 

# 리스트 내장객체(list comprehension) 
# [표현식 for 변수 in 자료형] 

y = [i * 2 for i in range(1, 11)]
y

 

# 예제 1) x 값, y 값 각각 곱한 값을 result 에 출력하세요.

x = [1,2,3]
y = [4,5,6]

[4, 5, 6, 8, 10, 12, 12, 15, 18]

# 1. 
for i in x:
    for j in y:
        print(i*j)

 

# 예제 2)

result = []
for i in x:
    for j in y:
        result.append(i*j)
result

 

# 예제 3) 리스트 내장객체

result = [i*j for i in x for j in y]
result

 

# [표현식(True값) for 변수 in 자료형 if 조건문]
# [표현식(True값) if 조건문 else 표현식(False값) for 변수 in 자료형]
# 예제) 3글자 이상의 과일만 담기

fruits = ["사과", "오렌지", "배", "귤", "포도", "바나나", "키위", "딸기", "망고", "샤인머스켓"]
fruits_lst = []

for i in fruits:
    if len(i) >= 3:
        fruits_lst.append(i)

fruits_lst

[i for i in fruits if len(i) >= 3]

 

# 음수 값만 담기

x = [2, -10, 5, -9, 5, -3]
negative = []

for i in x:
    if i < 0:
        negative.append(i)
negative

 

# true 값만 담기

[i for i in x if i < 0]

 

# 숫자 음수값을 문자 '음수'로 변경하기

x = [2, -10, 5, -9, 5, -3]
y = [2, '음수', 5, '음수', 5, '음수']

y =[]

for i in x:
    if i < 0:
        y.append('음수')
    else:
        y.append(i)
y

 

# 리스트 내장객체 이용, if-esle 문을 사용시, for문 앞에 작성

[i if i >= 0 else "음수" for i in x]
["음수" if i < 0 else i for i in x]
728x90
반응형
LIST