728x90
반응형

배경

 - 어떤 A 라는 리스트에 포함된 원소 중, 다른 리스트 B에 포함된 원소만 빼고 싶을 때,

 - 즉 집합간 빼기 연산처럼 A에서 A와 B의 교집합을 빼고 싶을 때 사용할 수 있는 방법

 - 다음과 같이 ListA (자연수)에서 ListB (홀수)를 빼서 짝수 리스트를 얻으려고 할 때, 리스트간 빼기 연산은 사용 불가

 - 지원되지 않는 연산으로 TypeError가 발생 (TypeError: unsupported operand type(s) for -: 'list' and 'list')

Python code

1
2
3
4
5
6
ListA = [1,2,3,4,5,6,7,8,9,10# 자연수
ListB = [1,3,5,7,9# 홀수
 
ListC = ListA - ListB # 자연수에서 홀수를 빼서 짝수를 얻고 싶은데...
 
print(ListC)
 
cs

Output

1
2
3
4
5
6
Traceback (most recent call last):
  File "C:/Users/wooan/PycharmProjects/blog/venv/main.py", line 4, in <module>
    ListC = ListA - ListB # 자연수에서 홀수를 빼서 짝수를 얻고 싶은데...
TypeError: unsupported operand type(s) for -: 'list' and 'list'
 
Process finished with exit code 1
cs

 

방법

 - for 반복문으로 리스트를 선언하는 방식과 if 문을 결합 (ListC)

 - 순서가 상관 없다면 집합으로 만들어서 구현 가능 (ListD)

 - if not 대신 if 를 사용하면 두 리스트의 교집합도 얻을 수 있다. (ListE)

Python code

1
2
3
4
5
6
7
8
9
10
ListA = [10,9,8,7,6,5,4,3,2,1# 자연수
ListB = [1,3,5,7,9# 홀수
 
ListC = [x for x in ListA if x not in ListB] # ListB에 포함되어 있지 않을 때만 ListA의 원소를 추가
ListD = list(set(ListA) - set(ListB)) # 집합으로 만들어 빼기
ListE = [x for x in ListA if x in ListB] # ListB에 포함되있을 경우만 ListA의 원소를 추가
 
print("ListC:", ListC)
print("ListD:", ListD)
print("ListE:", ListE)
 
cs

Output

1
2
3
4
5
ListC: [10, 8, 6, 4, 2]
ListD: [2, 4, 6, 8, 10]
ListE: [9, 7, 5, 3, 1]
 
Process finished with exit code 0
cs
728x90
반응형

+ Recent posts