Подтвердить что ты не робот

Как подсчитать уникальные значения в списке

Итак, я пытаюсь сделать эту программу, которая попросит пользователя ввести и сохранить значения в массиве/списке.
Затем, когда пустая строка будет введена, она сообщит пользователю, сколько из этих значений уникально.
Я строю это по причинам реальной жизни, а не как проблема.

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:

.. и это обо всем, что я получил до сих пор.
Я не уверен, как подсчитать уникальное количество слов в списке? Если кто-то может опубликовать решение, чтобы я мог учиться на нем, или, по крайней мере, показать мне, как это было бы здорово, спасибо!

4b9b3361

Ответ 1

Кроме того, используйте collection.Counter для рефакторинга вашего кода:

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]

Ответ 2

Вы можете использовать set для удаления дубликатов, а затем len для подсчета элементов в наборе:

len(set(new_words))

Ответ 3

Используйте set:

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

Ответ 4

values, counts = np.unique(words, return_counts=True)

Ответ 5

Для ndarray есть простой метод unique:

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])

Для Серии есть вызов функции value_counts():

Series_name.value_counts()

Ответ 6

ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list
unique_words = set(words)

Ответ 7

Хотя набор является самым простым способом, вы также можете использовать 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

Ответ 8

Следующее должно работать. Функция лямбда отфильтровывает дублированные слова.

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'

Ответ 9

Я бы использовал набор самостоятельно, но здесь еще один способ:

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!"

Ответ 10

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!"

Ответ 11

Другой метод с использованием панд

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"])

Затем вы можете экспортировать результаты в любой формат, который вы хотите

Ответ 12

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}