반응형
파이썬 코드를 짜다보면, 리스트의 모든 요소에서 n씩 빼거나 더해야 하는 경우가 있다.
예를 들어, 주어진 값을 그대로 인덱스 처럼 쓰고 싶다면 -1을 해줘야 인덱스와 값이 같아진다거나..
그래서 리스트에서 n씩 빼는 방법 2가지를 정리해보았다. n은 1로 두었다.
1. 리스트 컴프리헨션(List Comprehension) 사용
a = [1,2,3]
b = [i-1 for i in a]
print(b) # [0, 1, 2]
2. map 함수 사용
a = [1, 2, 3]
b = list(map(lambda x: x-1, a))
print(b) # [0, 1, 2]
2차원 리스트에서도 아래와 같은 방법들로 모든 요소에서 1씩 뺄 수 있다.
1. 리스트 컴프리헨션(List Comprehension)만 사용
a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
b = [[j-1 for j in i] for i in a]
print(b) # [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
2. map 함수와 리스트 컴프리헨션(List Comprehension) 사용
a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
b = list(map(lambda x: [i-1 for i in x], a))
print(b) #[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
반응형
'코딩 > 파이썬' 카테고리의 다른 글
[프로그래머스] 네트워크 풀이 - Python3 (0) | 2024.04.14 |
---|---|
[Python3] AttributeError: 'list' object has no attribute 'find' 오류 해결 방법 (0) | 2024.04.12 |
텐서플로우 set_random_seed 함수 에러, AttributeError: module 'tensorflow' has no attribute 'set_random_seed' 해결 방법 (0) | 2024.03.28 |
[Python] boto3 환경 설정, AWS CLI 설치하기 (0) | 2024.01.16 |
plt.savefig 함수에서의 must be real number, not str 오류 발생 (0) | 2024.01.09 |