[python]파이썬: 리스트 중복된 값 구하기
리스트 중복된 값 구하기
리스트 중복된 값을 구하는 방법은 여러가지가 있습니다.1.
word_list = ["123", "테스트", "test", "123", "테스트", "test123", "중복", "중복"]
word_cnt = dict()
for word in word_list:
if word not in word_cnt.keys():
word_cnt[word] = 1
else:
word_cnt[word] += 1
print(word_cnt)
# 출력
# {'123': 2, '테스트': 2, 'test': 1, 'test123': 1, '중복': 2}
word가 word_cnt에 존재하지 않는다면 처음으로 word가 나왔다는 뜻이므로 1을 선언합니다.
word가 word_cnt에 존재한다면 중복된다는 뜻이기 때문에 word가 한번더 나왔음을 알기 위해 +1을 해줍니다.
if word not in word_cnt.keys():
word_cnt[word] = 1
word가 word_cnt에 존재한다면 중복된다는 뜻이기 때문에 word가 한번더 나왔음을 알기 위해 +1을 해줍니다.
else:
word_cnt[word] += 1
2.
word_list = ["123", "테스트", "test", "123", "테스트", "test123", "중복", "중복"]
word_cnt = dict()
for word in list(set(word_list)):
word_cnt[word] = word_list.count(word)
print(word_cnt)
# 출력
# {'123': 2, '테스트': 2, 'test': 1, 'test123': 1, '중복': 2}
word_cnt = dict()
for word in list(set(word_list)):
word_cnt[word] = word_list.count(word)
print(word_cnt)
# 출력
# {'123': 2, '테스트': 2, 'test': 1, 'test123': 1, '중복': 2}
중복되는 단어들을 제거합니다. (검색 횟수 최소화)
for word in list(set(word_list)):
list에서 제공하는 count 함수를 사용합니다.
count 함수를 통해 word_list에 존재하는 word의 수를 세어준 뒤 word_cnt에 넣어줍니다.
for word in word_list:
word_cnt[word] = word_list.count(word)
3.
from collections import Counter
word_list = ["123", "테스트", "test", "123", "테스트", "test123", "중복", "중복"]
result = Counter(word_list)
print(result)
print(result.keys())
print(result.values())
# 출력
# Counter({'123': 2, '테스트': 2, '중복': 2, 'test': 1, 'test123': 1})
# dict_keys(['123', '테스트', 'test', 'test123', '중복'])
# dict_values([2, 2, 1, 1, 2])
word_list = ["123", "테스트", "test", "123", "테스트", "test123", "중복", "중복"]
result = Counter(word_list)
print(result)
print(result.keys())
print(result.values())
# 출력
# Counter({'123': 2, '테스트': 2, '중복': 2, 'test': 1, 'test123': 1})
# dict_keys(['123', '테스트', 'test', 'test123', '중복'])
# dict_values([2, 2, 1, 1, 2])
Counter는 자동으로 key, values 쌍으로 단어를 검색합니다.
result = Counter(word_list)
keys()를 통해 key 값만 출력할 수 있습니다.
result.keys()
values()를 통해 value 값만 출력할 수 있습니다.
result.values()
댓글
댓글 쓰기