파이썬에서 리스트를 간결하게 생성하는 방법. 반복문과 조건문을 사용하여 리스트를 만들 수 있다.
# 일반적인 방법
squares = []
for i in range(1, 6):
squares.append(i**2)
#리스트 컴프리헨션 사용
squares_comprehension = [i**2 for i in range(1, 6)]
print(squares) # 출력: [1, 4, 9, 16, 25]
print(squares_comprehension) # 출력: [1, 4, 9, 16, 25]
# 강의 사용 예시
# list comprehension
song_list = [dict(zip(column_names , song_tuple)) for song_tuple in cursor.fetchall()]
# 일반 for문
for song_tuple in cursor.fetchall():
song_dict = dict(zip(column_names, song_tuple))
song_list.append(song_dict)
<style>
form {margin-bottom: 10px}
form input { width: 100%; }
</style>
<!--
* {margin-bottom: 10px} : 태그 간 사이간격
-->
<form action="" method="get" autocomplete="off">
<input type="text" name="query" placeholder="검색어를 입력해주세요" autofocus
value="{{ query }}"
>
</form>
<!--
name="query" : 서버로 전송되는 값은의 이름은 query
value="{{ query }}" : 입력값 유지
autocomplete="off" : 이전의 입력값 자동완성 기능
-->
def index(request):
query = request.GET.get("query", "").strip() # 요청온 query 값이 있으면 get하고 없으면 "" 빈문자열 반환. 즉 검색어
json_url = "https://raw.githubusercontent.com/pyhub-kr/dump-data/main/melon/melon-20230906.json"
response = requests.get(json_url)
song_list = response.json()
if query:
song_list = filter(
lambda song: query in song['가수'], song_list
)
return render(request, "index.html", {"song_list": song_list, "query": query})
# filter(필터링 조건 함수, 필터링할 목록)