0

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?

klaas hansen
  • 3
  • 1
  • 2

2 Answers2

4

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']}
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
1

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.

Carles Mitjans
  • 4,786
  • 3
  • 19
  • 38