티스토리 뷰
ex) 리스트의 값들을 1씩 더한 리스트를 만들때
numbers = [1,2,3]
#1. 지금까지 방법 예
new_numbers = []
for num in numbers:
add_1 = num + 1
new_numbers.append(add_1)
#2. List Comprehension
#new_list = [ new_item for item in list ]
new_numbers = [ num+1 for num in numbers ]
---------------------------------------------------------
print(new_numbers)
[2, 3, 4]
ex)
name = "Kio"
for i in name:
print(i)
--------------------
K
i
o
new_list = [i for i in name]
print(new_list)
-------------------------------
['K', 'i', 'o']
ex) range(1,6)으로 값이 두배가 되는 숫자 리스트 만들기
double = [ num * 2 for num in range(1,6)]
print(double)
--------------------------------------------------------------
[2, 4, 6, 8, 10]
#3. Conditional List Comprehension
#new_list = [ new_item for item in list if test ]
ex) 4자 이하의 이름을 리스트로 만들기
name = ["Alex", "Benjamin", "Carl", "David", "Kio", "Freebee"]
short_name = [ n for n in name if len(n) < 5 ]
print(short_name)
--------------------------------------------------------
['Alex', 'Carl', 'Kio']
long_name = [ n.upper() for n in name if len(n) >= 5]
print(long_name)
----------------------------------------------------------------
['BENJAMIN', 'DAVID', 'FREEBEE']
* 연습문제
file1.txt 와 file2.txt에서 공통적으로 포함된 '숫자'를 List Comprehension으로 나타내 보아라
with open("file1.txt") as data1:
file1 = data1.readlines()
# number1=[]
# for data in file1:
# number1.append(int(data))
with open("file2.txt") as data2:
file2 = data2.readlines()
# number2=[]
# for data in file2:
# number2.append(int(data))
result = [ int(n1) for n1 in file1 if n1 in file2 ]
print(file1)
print(file2)
print("---------------------------------------------------")
print(result)
[output]
['3\n', '6\n', '5\n', '8\n', '33\n', '12\n', '7\n', '4\n', '72\n', '2\n', '42\n', '13\n']
['3\n', '6\n', '13\n', '5\n', '7\n', '89\n', '12\n', '3\n', '33\n', '34\n', '1\n', '344\n', '42\n']
---------------------------------------------------
[3, 6, 5, 33, 12, 7, 42, 13]
'Test > Python(20220101~)' 카테고리의 다른 글
Days26. 입력하는 영단어를 NATO Phonetic Alphabet 으로 변환 (0) | 2022.03.26 |
---|---|
Days26. Dictionary Comprehension (0) | 2022.03.17 |
cf. Get mouse click coordinates in Python turtle (0) | 2022.03.12 |
Days25. csv 데이터, pandas 라이브러리 (0) | 2022.03.08 |
Days24. 메일 머지(mail merge) (0) | 2022.03.07 |
- Total
- Today
- Yesterday
- 배열
- 부동없이
- 차집합
- virt-sysprep
- 3par
- oracle
- dp-1
- LIST
- 대소문자
- storage
- Join
- powershell
- 중복제거
- dp-2
- 읽어오기
- dezoomify
- vmware.powercli
- cloud-init
- insert
- EXA
- 스토리지
- set()
- 정렬
- exadata
- powercli
- vmware
- 변수화
- sysprep
- artandculture
- fromkeys
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |