Python

Python – List 정리2 (정렬, 조합, 기타)

리스트 정렬

  • list 정렬(reverse) – 값 역전
a = [3, 1, 5]
a.reverse()
a
>>> [5, 1, 3]
  • list 정렬(sort) – desc(내림차순)
a = [3, 5, 1]
a.sort()
a
>>> [1, 3, 5]
a.sort(reverse = True)
a
>>> [5, 3, 1]
  • list 정렬(sorted) – 대상의 값을 직접 정렬하지않고 대상의 정렬 값을 반환
a = [3, 5, 1]
b = sorted(a)
b
>>> [5. 3. 1]
a
>>> [3, 5, 1]
  • list 정렬(reversed) – iterable 객체 반환
a = [3, 5, 1]
b = reversed(a)
b
>>> <list_reverseiterator object at 객체번호>
list(b)
>>> [1, 5, 3]
a
>>> [3, 5, 1]

리스트 조합

  • 리스트 내 문자의 조합 [중복허용]
import itertools 
items = ['1', '2', '3', '4', '5'] 

print(list(itertools.permutations (items, 2)))
# [('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '1'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '1'), ('3', '2'), ('3', '4'), ('3', '5'), ('4', '1'), ('4', '2'), ('4', '3'), ('4', '5'), ('5', '1'), ('5', '2'), ('5', '3'), ('5', '4')]
  • 리스트 내 문자의 조합 [중복제거]
import itertools 
items = ['1', '2', '3', '4', '5'] 

print(list(itertools.combinations(items, 2)))

# [('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')]

  • 리스트 간의 조합
import itertools 
items = [['1', '2', '3', '4'], ['5', '6', '7', '8']] 

print(list(itertools.product(*items)))
# [('1', '5'), ('1', '6'), ('1', '7'), ('1', '8'), ('2', '5'), ('2', '6'), ('2', '7'), ('2', '8'), ('3', '5'), ('3', '6'), ('3', '7'), ('3', '8'), ('4', '5'), ('4', '6'), ('4', '7'), ('4', '8')]
  • 리스트를 문자열로 조합
items = ['1', '2', '3']
items = ''.join(items)
print(items)
# 123

기타 메서드 & 연산자

  • list length
i = [1,3,5]
len(i)
>>> 3
  • list count
i = [1, 1, 1, 3, 4, 5, 5]
i.count(5)
>>> 2
  • 복사
a = [1,2]
c = a.copy() # 복사1
v = list(c) # 복사2
all = a[:] # 복사3
  • is 연산자
c == v # 같은 값인가
>> True
c is v # 같은 변수인가
>> False
  • in 연산자
1 in [11, 22]
>>> False
  • 중복 제거
arr = [6, 5, 6, 4, 4, 1, 1, 2, 3, 9, 8, 7, 9, 8, 7] 

result = [] 

# 중복 제거된 값들이 들어갈 리스트 
for value in arr: 
   if value not in result: 
      result.append(value) 
      print(result)

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 항목은 *(으)로 표시합니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.