2 minute read

파이썬 복습이므로 헷갈리는 부분만 작성

리스트 관련 함수

zip()

questions = ['name', 'quest', 'color', 'name2']
answers = ['Kim', '파이썬', 'blue']
for q, a in zip(questions, answers):
	print(f"What is your {q}?  It is {a}")

insert()

인덱스 지정, 해장 인덱스 위치에 항목 삽입

heroes = ["아이언맨", "토르", "헐크"] 
heroes.insert(1, "스파이더맨") 
print(heroes)

index()

리스트 탐색

heroes = ["아이언맨", "토르", "헐크", "스칼렛 위치", "헐크"]
n = heroes.index("헐크")		# n은 2가 된다(첫 번째 요소 출력)
print(n)        # n = 2
  • 리스트 안에 찾는 값이 여러개 있는 경우 가장 첫번째 요소의 인덱스 출력
heroes = ["아이언맨", "토르", "헐크", "스칼렛 위치", "헐크"]
n = heroes.index("헐크", 3)		# 헐크를 찾는데 3부터 시작하라. n은 4가 된다. 
print(n)
  • index(value, n) 의 value값을 n번째 인덱스부터 탐색

sort()

리스트를 기본 오름차순으로 정렬

a = [3, 2, 1, 5, 4]
a.sort()
  • 역순 정렬을 원한다면 sort 매개변수로 reverse=True 전달
  • a 자체의 값이 변경됨

sorted(list)

내장함수를 이용한 정렬방법

numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
ascending_numbers = sorted(numbers)
  • numbers 자체의 순서는 바뀌지 않음
  • 값을 다른 변수에 저장해 주어야 함

random()

리스트에서 항목을 랜덤으로 검색

import random

numberList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("랜덤하게 선택한 항목=", random.choice(numberList))

리스트 비교

list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2)		# True

list1 = [0, 4, 5]
list2 = [1, 2, 3]
print(list1 > list2)  		# 전체 요소가 참일 때 참

리스트 복사: 깊은 복사

temps = [28, 31, 33, 35, 27, 26, 25] 
values = list(temps)

print(temps)			# temps 리스트 출력
values[3] = 39			# values 리스트 변경
print(temps)
print(values)
  • 얕은 복사는 values = temps 로 가능

리스트 슬라이싱

numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90]
numbers[::-1]       # 리스트가 역순으로 출력

라스트 함축

prices = [135, -545, 922, 356, -992, 217]
mprices = [i if i > 0 else 0 for i in prices]
print(mprices)      # [135, 0, 922, 356, 0, 217]

words = ["All", "good", "things", "must", "come", "to", "an", "end."]
letters = [w[-1] for w in words]
print(letters)      # ['l', 'd', 's', 't', 'e', 'o', 'n', '.']

numbers = [x + y for x in ['a','b','c'] for y in ['x','y','z']]
print(numbers)      # ['ax', 'ay', 'az', 'bx', 'by', 'bz', 'cx', 'cy', 'cz']

x = ['a'] 
y = ['x']
print(x + y)        # ['a', 'x']

Numpy 모듈

np.array()

numpy array 로 변경

import numpy as np

s = [[1, 2, 3, 4, 5],[6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
	 
s1 = np.array(s)
print(s1)