+ 1
Loop question, I've tried everything that I knew I just don't know. Please help me solve it out
How to I make a code that gives you how many are same in a list, using a loop, for example: Num = [1, 3, 2, 5, 7, 8, 7, 3, 1, 1] And it returns: 1 = 3 2 = 1 3 = 3 5 = 1 7= 2 8 = 1
8 ответов
+ 8
svnshqinz ,
here is a very basic approach without dictionary
> since numbers can occur multiple times in the input values, we have to take care that only the first occurrence of each
value is counted. to do so, we need a helpers list *already_seen*, where we can append numbers that have been already
counted.
> we start a for loop, that gets one number at a time from the input list and is stored in a loop variable variable like *num*
> inside the loop, we check if the current number is NOT already seen. this can be done with an *if* conditional and using
the *in* operator.
> if the current number is not in *already_seen*, we can output the result with print(...)
to get the count of the specific number, we can use the string.method count(...) like:
... nums.count(num)
> after this, we have to append the current number (variable *num*) to list *already_seen*
> if the loop is terminated, all numbers with the counts have been printed
+ 7
another thing i wanted to mention:
it is not seen as very helpful when we are going to post a ready-made code, as long as the op has not shown his attempt here.
it is more helpful to give hints and tips, so that the op has a chance to find a solution by himself.
+ 3
Should the output be in sorted form like that 1 = 3 ... 8 = 1?
+ 3
svnshqinz
Create a set from <Num> list to get only unique elements name it <num_set>
Then create a list named <sorted_num> from <num_set> and sort the list
Next, create a dictionary named <num_freq> where each item key is the value obtained from <sorted_num>, and item value is the frequency of the value in <Num> list.
Lastly, display the numbers and their frequency you have collected in <num_freq> dictionary
You can try this for now, or ask others how their code example work : )
+ 2
Ipang yes
+ 2
Ipang thank you! Actually it didnt need to be sorted but I was to distracted and didn't notice :)
+ 1
Num = [1, 3, 2, 5, 7, 8, 7, 3, 1, 1]
print(*[f'{n} = {Num.count(n)}' for n in sorted(set(Num))],sep='\n')
+ 1
Lothar, ok thank you very much :)