filmov
tv
Python Tutorial: List comprehension in Python

Показать описание
Problem statement:
Count the number of occurrences for each element in the list.
input = a=[1,2,2,3,4,4,4,5]
Output
1 = 1
2 = 2
3 = 1
4 = 3
5 = 1
Solution
a=[1,2,2,3,4,4,4,5]
temp=[]
for item in a:
if item not in temp:
"""List Comprehension"""
a=sorted(a)
last_ele=None
for index, item in enumerate(a):
if item != last_ele:
last_ele=item
temp=[]
for item in a:
count=0
for j in a:
if item == j:
count +=1
if item not in temp:
print(f"{item} = {count}")
Count the number of occurrences for each element in the list.
input = a=[1,2,2,3,4,4,4,5]
Output
1 = 1
2 = 2
3 = 1
4 = 3
5 = 1
Solution
a=[1,2,2,3,4,4,4,5]
temp=[]
for item in a:
if item not in temp:
"""List Comprehension"""
a=sorted(a)
last_ele=None
for index, item in enumerate(a):
if item != last_ele:
last_ele=item
temp=[]
for item in a:
count=0
for j in a:
if item == j:
count +=1
if item not in temp:
print(f"{item} = {count}")