|
发表于 2023-2-25 22:48:58
|
显示全部楼层
本帖最后由 chinajz 于 2023-2-25 23:10 编辑
- def get_counts(x):
- counts={}
- for n in x:
- if n in counts:
- counts[n] += 1
- else:
- counts[n] = 1
- return counts
- #words = input("input words: ").split()
- words = ' key1 key1 key2 key3 value2 key1 key2 key1 value1 value3 key1'.split()
- print ('words:',words)
- valuex = ''
- for i in range (len(words)):
- a = words[i]
- b = words[i].strip('k')
- if a is not b :
- valuex += a + ','
- value1 = valuex[:-1].split(',')
- print ("value1=",value1)
- value2 =get_counts(value1)
- print('value2=',value2)
- n = 0
- swap = ''
- for i in value2:
- m = int(value2[i])
- if n <= m:
- n= value2[i]
- swap = i
- print('max_key_value : ',swap,':',n)
复制代码
运行结果:
- #input words: key1 key1 key2 key3 value2 key1 key2 key1 value1 value3 key1
- words: ['key1', 'key1', 'key2', 'key3', 'value2', 'key1', 'key2', 'key1', 'value1', 'value3', 'key1']
- value1= ['key1', 'key1', 'key2', 'key3', 'key1', 'key2', 'key1', 'key1']
- value2= {'key1': 5, 'key2': 2, 'key3': 1}
- max_key_value : key1 : 5
复制代码 |
|