count number of names in list in python [duplicate] - python

This question already has answers here:
How to count the frequency of the elements in an unordered list? [duplicate]
(33 answers)
Closed 5 years ago.
i have one list wich has names in it:
names = ['test','hallo','test']
uniquenames = ['test','hallo']
with set i get the uniquenames so the unique names are in a different list
but now i want to count how many names there are of each so test:2 hallo:1
i have this:
for i in range(len(uniquenames)):
countname = name.count[i]
but it gives me this error:
TypeError: 'builtin_function_or_method' object is not subscriptable
how can i fix that?

You could use a dictionary:
names = ['test','hallo','test']
countnames = {}
for name in names:
countnames[name] = countnames.get(name, 0) + 1
print(countnames) # => {'test': 2, 'hallo': 1}
If you want to make it case-insensitive, use this:
names = ['test','hallo','test', 'HaLLo', 'tESt']
countnames = {}
for name in names:
name = name.lower() # => to make 'test' and 'Test' and 'TeST'...etc the same
countnames[name] = countnames.get(name, 0) + 1
print(countnames) # => {'test': 3, 'hallo': 2}
In case you want the keys to be the counts, use an array to store the names in:
names = ['test','hallo','test','name', 'HaLLo', 'tESt','name', 'Hi', 'hi', 'Name', 'once']
temp = {}
for name in names:
name = name.lower()
temp[name] = temp.get(name, 0) + 1
countnames = {}
for name, count in temp.items():
countnames.setdefault(count, []).append(name)
print(countnames) # => {3: ['test', 'name'], 2: ['hallo', 'hi'], 1: ['once']}

Use Counter from collections:
>>> from collections import Counter
>>> Counter(names)
Counter({'test': 2, 'hallo': 1})
Also, for your example to work you should change names.count[i] for names.count(i) as count is a function.

Related

Unable to process dict properly

I have dict which got list, what I want is to display list elements in one line.
My dict
data = {'id':[1,2], 'name':['foo','bar'], 'type':['x','y']}
Expected output
name is foo and id is 1
name is bar and id is 2
My code
>>> data = {'id':[1,2], 'name':['foo','bar'], 'type':['x','y']}
>>> for key, value in data.items():
... print(value)
...
['foo', 'bar']
['x', 'y']
[1, 2]
>>>
You can use zip() as:
for name, idx in zip(data['name'], data['id']):
print(f"name is {name} and id is {idx}")
Use format() if you are using python version lower than 3.6:
for name, idx in zip(data['name'], data['id']):
print("name is {0} and id is {1}".format(name, idx))

Python - Automatically create new variables based on other variable [duplicate]

This question already has answers here:
How to declare many variables?
(5 answers)
Closed 3 years ago.
I would like to do something like this:
for i in range(0, 3):
if i == 0:
name_i = "A"
elif i == 1:
name_i = "B"
else:
name_i = "C"
to have name_o = "A", name_1 = "B", name_i = "C".
I know I cannot do it like that method but is there some trick I can use to achieve that?
Dict example:
names = ['A', 'B', 'C']
my_dict = {}
for n, i in enumerate(names):
name = 'name_{}'.format(n)
my_dict[name] = i
Output:
{'name_0': 'A', 'name_1': 'B', 'name_2': 'C'}
Depending on where you get your A, B, C from, you can simply take them out of a list.
# or wherever your letters / whatever come from
import string
abc = string.ascii_uppercase
name0, name1, name2 = abc[0: 3]
print(name0)
print(name1)
print(name2)

Count how many different kinds of elements in python list [duplicate]

This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 4 months ago.
So I'm trying to make this program that will ask the user for input and store the values in an array / list.
Then when a blank line is entered it will tell the user how many of those values are unique.
I'm building this for real life reasons and not as a problem set.
enter: happy
enter: rofl
enter: happy
enter: mpg8
enter: Cpp
enter: Cpp
enter:
There are 4 unique words!
My code is as follows:
# 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:
..and that's about all I've gotten so far.
I'm not sure how to count the unique number of words in a list?
If someone can post the solution so I can learn from it, or at least show me how it would be great, thanks!
In addition, use collections.Counter to refactor your code:
from collections import Counter
words = ['a', 'b', 'c', 'a']
Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency
Output:
['a', 'c', 'b']
[2, 1, 1]
You can use a set to remove duplicates, and then the len function to count the elements in the set:
len(set(new_words))
values, counts = np.unique(words, return_counts=True)
More Detail
import numpy as np
words = ['b', 'a', 'a', 'c', 'c', 'c']
values, counts = np.unique(words, return_counts=True)
The function numpy.unique returns sorted unique elements of the input list together with their counts:
['a', 'b', 'c']
[2, 1, 3]
Use a set:
words = ['a', 'b', 'c', 'a']
unique_words = set(words) # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3
Armed with this, your solution could be as simple as:
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}
For ndarray there is a numpy method called unique:
np.unique(array_name)
Examples:
>>> 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])
For a Series there is a function call value_counts():
Series_name.value_counts()
If you would like to have a histogram of unique values here's oneliner
import numpy as np
unique_labels, unique_counts = np.unique(labels_list, return_counts=True)
labels_histogram = dict(zip(unique_labels, unique_counts))
How about:
import pandas as pd
#List with all words
words=[]
#Code for adding words
words.append('test')
#When Input equals blank:
pd.Series(words).nunique()
It returns how many unique values are in a list
You can use get method:
lst = ['a', 'b', 'c', 'c', 'c', 'd', 'd']
dictionary = {}
for item in lst:
dictionary[item] = dictionary.get(item, 0) + 1
print(dictionary)
Output:
{'a': 1, 'b': 1, 'c': 3, 'd': 2}
ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list
unique_words = set(words)
Although a set is the easiest way, you could also use a dict and use some_dict.has(key) to populate a dictionary with only unique keys and values.
Assuming you have already populated words[] with input from the user, create a dict mapping the unique words in the list to a number:
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
Other method by using pandas
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"])
You can then export results in any format you want
The following should work. The lambda function filter out the duplicated words.
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'
I'd use a set myself, but here's yet another way:
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!"
This is my own version
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)

Python: Counting String frequency list type [duplicate]

This question already has answers here:
Counting occurrences without using collections.Counter
(5 answers)
Closed 5 years ago.
I am using python to count the frequency of list WITHOUT using any collection just solely my own python basics functions.
My code is:
my_list = ['a', 'b','a', 'a','b','b', 'a','a','c']
def counting():
#Please help
Print out put should be like
a: 5
b: 3
c: 1
Please help thank you.
Use count , an inbuilt list function.
def counting(my_list):
return { x:my_list.count(x) for x in my_list }
Just call it :
>>> counting(my_list)
=> {'a': 5, 'b': 3, 'c': 1}
#print it as per requirement
>>> for k,v in counting(my_list).items():
print(k,':',v)
a : 5
b : 3
c : 1
#driver value :
IN : my_list = ['a', 'b','a', 'a','b','b', 'a','a','c']
Create a dictionary to hold the results and check if the key exists increment the value, otherwise set the value of 1 (first occurrence).
my_list = ['a', 'b','a', 'a','b','b', 'a','a','c']
def counting(my_list):
counted = {}
for item in my_list:
if item in counted:
counted[item] += 1
else:
counted[item] = 1
return counted
print(counting(my_list))

Python: Can one create new variable names from a list of strings? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I'm new to python, so I don't know if this is possible. I'm trying to create a list of variable names from a list of strings so I can then assign values to the newly created variables.
I saw another similar question, but there was already a dict pays of keys and values.
Here's my code:
def handy(self):
a = raw_input('How many hands? ')
for i in range(int(a)):
h = "hand" + str(i+ 1)
self.list_of_hands.append(h)
# would like to create variable names from self.list_of_hands
# something like "hand1 = self.do_something(i)"
print h
print self.list_of_hands
Given some of the answers, i'm adding the following comment:
I'm going to then assign dicts to each variable. So, can I create a dictionary of dictionaries?
Why don't you just construct a dictionary using the strings as keys?
>>> class test():
def handy(self):
a = raw_input('How many hands? ')
d = { "hand" + str(i + 1) : self.do_something(i) for i in range(int(a)) }
keys = d.keys()
keys.sort()
for x in keys:
print x, '=', d[x]
def do_something(self, i):
return "something " + str(i)
>>> test().handy()
How many hands? 4
hand1 = something 0
hand2 = something 1
hand3 = something 2
hand4 = something 3
Edit: You updated the question to ask if you can store a dictionary as a value in a dictionary. Yes, you can:
>>> d = { i : { j : str(i) + str(j) for j in range(5) } for i in range(5) }
>>> d[1][2]
'12'
>>> d[4][1]
'41'
>>> d[2]
{0: '20', 1: '21', 2: '22', 3: '23', 4: '24'}
>> d[5] = { 1 : '51' }
>> d[5][1]
'51'
If you ever have multiple variables that only differ by a number at the end (hand1, hand2, etc.), you need a container.
I think a dictionary would work best:
self.hands = {}
self.hands[h] = self.do_something(i)
You can access the individual keys in the dictionary easily:
self.hands['hand1']
h = "hand" + str(i+ 1)
vars()[h] = do_something(i)
Now you can call hand1 to call do_something()

Categories