Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
count item in list
#1
Hello,
how can I count part of items in list?

to be clear :
I have a list that build in this form
Final_List= [['10.0.0.1:Success', '10.0.0.2:Success', '10.0.0.3:Error', '10.0.0.4:Offline' , '10.0.0.5:Error']]

I want to know how much Succes\error\offline there is in the list (i don't mind the IP - just the total number)
I have try to run

ok = 0
error = 0
offline = 0 
for item in IP_List:
    if 'Success' in item:
        ok +=1
    if 'Error' in item:
        error +=1 
    if 'offline' in item:
        offline += 1 
maybe I used list.appand wrong?
Final_List.append(p.map(GetUplaudFies, Device_List))
GetUplaudFies return this
 return ip + ":" + Upload_Status
Reply
#2
Use a counting dictionary.
import collections

items = ['A', 'B', 'A', 'B', 'C', 'A', 'A']
counter = collections.Counter(items)
for item, count in counter.items():
    print(item, count)
Output:
A 4 B 2 C 1
tester_V likes this post
Reply
#3
I saw this
but will it work ?
beacuse every item in the list is number:state
and I'm only want to count the state .

for my list will it not give me 200 results? I have 200 differents IP inside
Reply
#4
p.map is giving you a list, so there is no reason to append unless you want Final_List to be a list of lists. Your code fails because FinalList[0] is ['10.0.0.1:Success', '10.0.0.2:Success', '10.0.0.3:Error', '10.0.0.4:Offline' , '10.0.0.5:Error'], not '10.0.0.1:Success' as you are expecting. Change the code to something like this:
Final_List = p.map(GetUplaudFies, Device_List)
You can use a counter dictionary. But maybe it isn't right for this application since there are only 3 possible outcomes and they are all known. Your code should work with the above change. But this is a way to do it with a Counter
 outcomes = [outcome.split(':')[1] for outcome in Final_List]
outcomes = collections.Counter(outcomes)
for item, count in counter.items():
    print(item, count)
Reply
#5
i guees this was my mistake
the appand after the map
I didn't realize it create my a list

well - everyday you learn somehting :-)

thank you !
Reply
#6
The Counter from collections is helpful.

from collections import Counter


def my_filter(iterable):
    """
    Generator returns the state: 'Success', 'Error', 'Offline'
    """
    for element in iterable:
        try:
            ip, kind = element.split(":", maxsplit=1)
        except ValueError:
            continue

        yield kind


def get_results(chunks):
    """
    Yield all chunks as Counter object
    """
    for chunk in chunks:
        yield Counter(my_filter(chunk))


def sum_results(chunks):
    """
    Sum all chunks together and return one Counter object
    """
    final = Counter()
    for result in get_results(chunks):
        final += result

    return final



input_data = [
    [
        '10.0.0.1:Success',
        '10.0.0.2:Success',
        '10.0.0.3:Error',
        '10.0.0.4:Offline',
        '10.0.0.5:Error',
    ]
]


results1 = sum_results(input_data)
results2 = sum_results(input_data * 10)


print(results1)
print(results2)
Output:
Counter({'Success': 2, 'Error': 2, 'Offline': 1}) Counter({'Success': 20, 'Error': 20, 'Offline': 10})
If input_data is a flat list, get_results(input_data) does not require the for-loop and just return one Counter object.

FlatList-Example:
from collections import Counter


def my_filter(iterable):
    """
    Generator returns the state: 'Success', 'Error', 'Offline'
    """
    for element in iterable:
        try:
            ip, kind = element.split(":", maxsplit=1)
        except ValueError:
            continue

        yield kind


input_data = [
    '10.0.0.1:Success',
    '10.0.0.2:Success',
    '10.0.0.3:Error',
    '10.0.0.4:Offline',
    '10.0.0.5:Error',
]


result1 = Counter(my_filter(input_data))
result2 = Counter(my_filter(input_data * 10))
print(result1)
print(result2)
Output:
Counter({'Success': 2, 'Error': 2, 'Offline': 1}) Counter({'Success': 20, 'Error': 20, 'Offline': 10})
You should also read: https://docs.python.org/3/library/collec...ns.Counter
tester_V and Pedroski55 like this post
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#7
thanks
I will give it also a try
Reply
#8
What do you think should happen when you append a list to a list? Did you think it would make the original list longer? Append (and insert) treat the argument as an object, not an iterable. From the docs:
Quote:list.append(x)
Add an item to the end of the list. Equivalent to a[len(a):] = [x].
You could use extend to add items from a list to an existing list.
Output:
list.extend(iterable) Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable
And as the extend description from the manual hints, you can do the same thing with slices. You can also concatenate lists using '+'

Lists are important in Python. You need to REALLY understand how they work or it is going to come back to bite you again and again.
Reply
#9
items = ['A', 'B', 'A', 'B', 'C', 'A', 'A']
key = sorted(set(items))
for k in key:
    print(k, items.count(k))
Output:
A 4 B 2 C 1
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Time.sleep: stop appending item to the list if time is early quest 0 497 Apr-13-2021, 11:44 AM
Last Post: quest
  list.count does not appear to function Oldman45 7 1,060 Mar-16-2021, 04:25 PM
Last Post: Oldman45
  Function to count words in a list up to and including Sam Oldman45 13 1,405 Feb-18-2021, 10:22 AM
Last Post: perfringo
  How to run a pytest test for each item in a list arielma 0 624 Jan-06-2021, 10:40 PM
Last Post: arielma
  List of error codes to find (and count) in all files in a directory tester_V 8 1,062 Dec-11-2020, 07:07 PM
Last Post: tester_V
  Count number of occurrences of list items in list of tuples t4keheart 1 695 Nov-03-2020, 05:37 AM
Last Post: deanhystad
  How do I add a number to every item in a list? john316 2 518 Oct-28-2020, 05:29 PM
Last Post: deanhystad
  Ignoring a list item hank4eva 2 804 Aug-17-2020, 08:40 AM
Last Post: perfringo
  Select correct item from list for subprocess command pythonnewbie138 6 1,052 Jul-24-2020, 09:09 PM
Last Post: pythonnewbie138
  Why is the item not in list when it is DanielCook 2 732 Jul-08-2020, 07:38 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020