简体   繁体   中英

Listing names to arrays

o = [1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5]

I want to be able to show how many 1s, 2s and so on.

For example if there is 6 1 , it will print BendingF = 6 . My 1 , 2 , 3 , 4 , 5 are different positions. 1 = BendingF , 2 = BendingM , 3 = Twisting , 4 = Walking , 5 = Squat .

I tried

##1 = print('Bending Forward')
##2 = print('Bending Midway')
##3 = print('Twisting')
##4 = print('Walking')
##5 = print('Squating')

but it will give me error:

SyntaxError: can't assign to literal

As @Amadan mentioned you can use Counter to count each occurrence of unique numbers in your array. Then create a dictionary ( labels ) to map your integers to the string values that they would represent:

from collections import Counter

o = [1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5]

labels = {
  1: 'Bending Forward',
  2: 'Bending Midway',
  3: 'Twisting',
  4: 'Walking',
  5: 'Squating'
}

count = Counter(o)

for val in count.keys():
  print(labels[val] + " - " + str(count[val]))

Outputs

 Bending Forward - 9
 Bending Midway - 8
 Twisting - 16
 Walking - 11
 Squating - 8

Repl link

o = [1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5]
print("Bending forward = " + str(o.count(1)))
print("Bending Midway = " + str(o.count(2)))
print("Twisting = " + str(o.count(3)))
print("Walking = " + str(o.count(4)))
print("Squatting = " + str(o.count(5)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM