With a list like this: ["Apple", "Banana", "Peach", "Apple", "Banana", "Orange"]
I tried to pass the list to a function and sort it as follows:
def l(fruits):
for i in fruits:
print(i)
n = ["Apple", "Banana", "Peach", "Apple", "Banana", "Orange"]
l(sorted(n))
I only got the result like this:
Apple
Apple
Banana
Banana
Orange
Peach
I am wondering how to count the occurrence of each item in the list respectively to get the output like this:
Apple 2
Banana 2
Orange 1
Peach 1
I know using collections.Counter
can get a similar result, however, I would like the output to be the same as above.
Edit: I just found out the items in the list should be in lower case.
Also, I tried doing it without collections_counter
def fruit_list(fruits):
for i in fruits:
fruit_occurence = fruits.count("apple")
fruit_occurence2 = fruits.count("banana")
fruit_occurence3 = fruits.count("peach")
fruit_occurence4 = fruits.count("orange")
if i == "apple":
print(i.title(), *{fruit_occurence})
elif i == "banana":
print(i.title(), *{fruit_occurence2})
elif i == "peach":
print(i.title(), *{fruit_occurence3})
elif i == "orange":
print(i.title(), *{fruit_occurence4})
f = ["apple", "banana", "peach", "apple", "banana", "orange"]
fruit_list(sorted(f))
Output:
Apple 2
Apple 2
Banana 2
Banana 2
Orange 1
Peach 1
Is there anyway to remove the duplicate items in the output? Changing the list to set would affect the fruit_occurances.
CodePudding user response:
You can use Counter
then use sorted
in for
in function
then use print(*...)
like below:
from collections import Counter
def l(fruits):
for i in sorted(Counter(fruits).items()):
print(*i)
n = ["Apple", "Banana", "Peach", "Apple", "Banana", "Orange"]
l(n)
Output:
Apple 2
Banana 2
Orange 1
Peach 1
CodePudding user response:
Use a collections.Counter
:
from collections import Counter
def l(fruits):
c = Counter(fruits)
for fruit, count in sorted(c.items()):
print(fruit, count)
CodePudding user response:
Without modifying l
at all,
>>> l(f'{f} {c}' for f, c in sorted(Counter(n).items()))
The trick is to create a generator expression that produces the strings you want to print from the Counter
instance.
CodePudding user response:
text = ["Apple", "Banana", "Peach", "Apple", "Banana", "Orange"]
dict = {}
def l(text):
for i in text:
dict[i] = text.count(i)
print(dict)
l(text)
CodePudding user response:
This should be work for you
import collections
fruits = ["Apple", "Banana", "Peach", "Apple", "Banana", "Orange"]
d = {}
for fruit in fruits:
if fruit in d:
d[fruit] = 1
else:
d[fruit] = 1
od = collections.OrderedDict(sorted(d.items()))
print (od)