리스트 내의 고유값 발생을 카운트하려면 어떻게 해야 합니까?
그래서 저는 사용자에게 입력을 요청하고 값을 배열/목록에 저장하는 이 프로그램을 만들려고 합니다.
그런 다음 공백 행을 입력하면 해당 값 중 고유 값이 몇 개인지 사용자에게 알려줍니다.
난 문제를 해결하기 위해서가 아니라 실생활에서 이걸 만들고 있는 거야.
enter: happy
enter: rofl
enter: happy
enter: mpg8
enter: Cpp
enter: Cpp
enter:
There are 4 unique words!
제 코드는 다음과 같습니다.
# ask for input
ipta = raw_input("Word: ")
# create list
uniquewords = []
counter = 0
uniquewords.append(ipta)
a = 0 # loop thingy
# while loop to ask for input and append in list
while ipta:
ipta = raw_input("Word: ")
new_words.append(input1)
counter = counter + 1
for p in uniquewords:
..그리고 그게 내가 지금까지 얻은 전부야.
목록에 있는 단어 수를 어떻게 세는지 모르겠어요.
누군가가 솔루션을 게시하여 제가 배울 수 있도록 하거나 적어도 얼마나 좋은지 보여주시면 감사하겠습니다!
from collections import Counter
words = ['a', 'b', 'c', 'a']
Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency
출력:
['a', 'c', 'b']
[2, 1, 1]
세트를 사용하여 중복을 제거한 후 len 함수를 사용하여 세트의 요소를 카운트할 수 있습니다.
len(set(new_words))
values, counts = np.unique(words, return_counts=True)
상세
import numpy as np
words = ['b', 'a', 'a', 'c', 'c', 'c']
values, counts = np.unique(words, return_counts=True)
numpy.unique 함수는 입력 목록의 정렬된 고유 요소를 카운트와 함께 반환합니다.
['a', 'b', 'c']
[2, 1, 3]
세트 사용:
words = ['a', 'b', 'c', 'a']
unique_words = set(words) # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3
이를 통해 다음과 같은 간단한 솔루션을 구현할 수 있습니다.
words = []
ipta = raw_input("Word: ")
while ipta:
words.append(ipta)
ipta = raw_input("Word: ")
unique_word_count = len(set(words))
print "There are %d unique words!" % unique_word_count
aa="XXYYYSBAA"
bb=dict(zip(list(aa),[list(aa).count(i) for i in list(aa)]))
print(bb)
# output:
# {'X': 2, 'Y': 3, 'S': 1, 'B': 1, 'A': 2}
ndarray에는 unique라는 numpy 메서드가 있습니다.
np.unique(array_name)
예:
>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])
시리즈에는 call value_counts() 함수가 있습니다.
Series_name.value_counts()
고유한 값의 히스토그램을 여기에 표시하려면 oneliner
import numpy as np
unique_labels, unique_counts = np.unique(labels_list, return_counts=True)
labels_histogram = dict(zip(unique_labels, unique_counts))
그럼 어떻게 해?
import pandas as pd
#List with all words
words=[]
#Code for adding words
words.append('test')
#When Input equals blank:
pd.Series(words).nunique()
목록에 있는 고유 값 수를 반환합니다.
사용할 수 있습니다.get
방법:
lst = ['a', 'b', 'c', 'c', 'c', 'd', 'd']
dictionary = {}
for item in lst:
dictionary[item] = dictionary.get(item, 0) + 1
print(dictionary)
출력:
{'a': 1, 'b': 1, 'c': 3, 'd': 2}
ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list
unique_words = set(words)
세트가 가장 쉬운 방법이지만 dict를 사용하여some_dict.has(key)
원하는 키와 값만 사전을 채웁니다.
이미 입력되어 있는 경우words[]
사용자의 입력을 사용하여 목록의 고유한 단어를 숫자에 매핑하는 dict를 만듭니다.
word_map = {}
i = 1
for j in range(len(words)):
if not word_map.has_key(words[j]):
word_map[words[j]] = i
i += 1
num_unique_words = len(new_map) # or num_unique_words = i, however you prefer
판다를 이용한 기타 방법
import pandas as pd
LIST = ["a","a","c","a","a","v","d"]
counts,values = pd.Series(LIST).value_counts().values, pd.Series(LIST).value_counts().index
df_results = pd.DataFrame(list(zip(values,counts)),columns=["value","count"])
원하는 형식으로 결과를 내보낼 수 있습니다.
다음 사항이 유효합니다.람다 함수는 중복된 단어를 필터링합니다.
inputs=[]
input = raw_input("Word: ").strip()
while input:
inputs.append(input)
input = raw_input("Word: ").strip()
uniques=reduce(lambda x,y: ((y in x) and x) or x+[y], inputs, [])
print 'There are', len(uniques), 'unique words'
저도 세트를 사용하고 싶지만, 또 다른 방법이 있습니다.
uniquewords = []
while True:
ipta = raw_input("Word: ")
if ipta == "":
break
if not ipta in uniquewords:
uniquewords.append(ipta)
print "There are", len(uniquewords), "unique words!"
ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list
while ipta: ## while loop to ask for input and append in list
words.append(ipta)
ipta = raw_input("Word: ")
words.append(ipta)
#Create a set, sets do not have repeats
unique_words = set(words)
print "There are " + str(len(unique_words)) + " unique words!"
이것은 나만의 버전입니다.
def unique_elements():
elem_list = []
dict_unique_word = {}
for i in range(5):# say you want to check for unique words from five given words
word_input = input('enter element: ')
elem_list.append(word_input)
if word_input not in dict_unique_word:
dict_unique_word[word_input] = 1
else:
dict_unique_word[word_input] += 1
return elem_list, dict_unique_word
result_1, result_2 = unique_elements()
# result_1 holds the list of all inputted elements
# result_2 contains unique words with their count
print(result_2)
언급URL : https://stackoverflow.com/questions/12282232/how-do-i-count-occurrence-of-unique-values-inside-a-list
'programing' 카테고리의 다른 글
Redux 스토어 상태를 리셋하는 방법 (0) | 2022.10.13 |
---|---|
jQuery.parseJSON이 JSON에서 이스케이프된 단일 따옴표로 인해 "Invalid JSON" 오류를 발생시킵니다. (0) | 2022.10.13 |
MySQLdb를 사용하여 커서를 닫아야 하는 경우 (0) | 2022.10.03 |
Larabel Migration을 사용하여 타임스탬프 열의 기본값을 현재 타임스탬프로 설정하려면 어떻게 해야 합니까? (0) | 2022.10.03 |
dict에서 값 목록을 가져오려면 어떻게 해야 합니까? (0) | 2022.10.03 |