-1
vote(['G', 'G', 'N', 'G', 'C'])

我想得到这个结果:('G', [1, 3, 0, 1])

g_count = 0
n_count = 0
l_count = 0
c_count = 0
for i in range(len(ballots)):
    if ballots[i] == 'G':
        g_count += 1
    elif ballots[i] =='N':
        n_count += 1
    elif ballots[i] == 'L':
        l_count +=1
    else:
        c_count += 1

return [n_count,g_count,l_count,c_count]

我如何获得前面的“G”?

4

1 回答 1

1

像这样的东西:

In [9]: from collections import Counter

In [15]: def vote(lis):
   ....:     c=Counter(lis)
   ....:     return c.most_common()[0][0],[c[x] for x in "NGLC"]
   ....: 

In [16]: vote(['G', 'G', 'N', 'G', 'C'])
Out[16]: ('G', [1, 3, 0, 1])

In [17]: vote(['G', 'G', 'N', 'G', 'C','L','L'])
Out[17]: ('G', [1, 3, 2, 1])

In [18]: vote(['G', 'L', 'N', 'G', 'C','L','L'])
Out[18]: ('L', [1, 2, 3, 1])

这里c.most_common()返回[('G', 3), ('C', 1), ('N', 1)],从这里就可以得到了'G'

于 2013-03-31T18:59:34.580 回答