본문 바로가기
카테고리 없음

Python List 연산 예제

by BABEL-II 2019. 11. 10.

# 리스트 아이템 중복 갯수 계산하기

a=[1,2,3,4]

b=[2,3,4,5]

d=[8]

e = [item for item in d if item in b]

print(len(e))

1

f = [item for item in a if item in b]

print(len(f))

3

c = [item for item in a if item not in b]

print(len(a)-len(c))

0

c = [item for item in d if item not in b]

print(len(d)-len(c))

1

추가 : 아래는 집합으로 변형해서 처리한다.

 

## 비교 list 정의

x = [1, 2, 3, 4, 5, 6]

y = [9, 8, 7, 6, 5, 6]

##################################################################################################################################

## 판별하는 방법 확인

## list를 집합(index없는)으로 변경하기 위해 set 또는 frozenset 처리 (frozenset이 더 빠르다고함...) / help(set) help(frozenset)

x_set = frozenset(x)

## x_set에서 y가 있는지 확인 하기 위해 intersection 함수 활용 / help(intersection)

a=x_set.intersection(y)

print(a)

print(len(a))

##################################################################################################################################

## 두 list를 비교하여 존재하는지 판별

if len(a) > 0:

print("존재함")

else :

print("존재하지 않음")

##################################################################################################################################

## 두 list를 비교하여 존재하는지 함수화

def campare_two_list(list1,list2):

list1 = list1

list2 = list2

intersec = frozenset(list1).intersection(list2)

if len(intersec)> 0:

print("존재함")

else :

print("존재하지 않음")

print("def결과")

campare_two_list(x,y)

##################################################################################################################################

## 두 list를 비교하여 존재하는지 class & 함수화

class find_element:

def __init__(self, list1, list2):

self.list1 = list1

self.list2 = list2

self.intersec = frozenset(self.list1).intersection(self.list2)

def campare_two_list(self):

if len(self.intersec)> 0:

print("존재함")

else :

print("존재하지 않음")

# class 할당

class_a = find_element(x,y)

print("class결과")

class_a.campare_two_list()