본문 바로가기
IT World/Python

Python Training Day 12. List Comprehensions

by 닷라인웨이 2022. 12. 25.

Chapter 14. List Comprehensions

 

List Comprehensions is a very powerful tool, which creates a new list based on another list, in a single, readable line.

 

for loops vs. list comprehension

# for loop
word_lengths = []
for word in words:
      if word != "the":
          word_lengths.append(len(word))

# list comprehension
word_lengths = [len(word) for word in words if word != "the"]

time comparison

2030개의 단어를 가진 String을 Input Data로 넣었을 때 for loop와 list comprehension의 결괏값 도출 경과 시간 차이를 Test 해 보았을 때, List Comprehension이 시간 측면에서 더욱 효율적인 것으로 나왔다.

 

 

import math

numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]

# ---CASE 1 : returns an int no larger than the input.---

# 1. int
newlist = [int(positive_num_int) for positive_num_int in numbers if positive_num_int >= 0]

# 2. math.floor
# newlist = [math.floor(positive_num_int) for positive_num_int in numbers if positive_num_int >= 0]

# 3. math.trunc
# newlist = [math.trunc(positive_num_int) for positive_num_int in numbers if positive_num_int >= 0]

# ---CASE 2 : returns the smallest integer larger than the input.---

# 1. math.ceil
#newlist = [math.ceil(positive_num_int) for positive_num_int in numbers if positive_num_int >= 0]

# 2. round
#newlist = [round(positive_num_int) for positive_num_int in numbers if positive_num_int >= 0]

print(newlist)

 

Exercise

정수 리스트를 생성하라고 했으니까 소수점 아래 숫자를 버림 하던지 반올림하던지 상관이 없어 두 경우 모두 정답으로 처리하는 듯하다.

댓글