Python:在列表中查找值

时间:2013-05-14 04:07:34

标签: python list

def sum_points(point_list):
    sol = []
    sum = 0.0
    for x in point_list:
        sum += x
    sol.append(sum)
    return sol

def main():
    with open("example.json") as f:
         for line in f:
             result = json.loads(line)
             if('text' and 'place' in result.keys()) and (type(result['place']) is dict):
                 place_user = result['place']
                 tw_user = result['text']

                 words = tw_user.encode("utf-8").split()
                 points = dict.fromkeys(words,0)

                 with open("wordlist.txt") as f:
                      for line in f:
                          key, val = line.split("\t")
                          if key in points:
                                 points[key.strip()] += int(val)
                 point_list = sum_points(points.values())
                 addr_code = place_user['full'].encode("utf-8").split()

从我的代码中,我得到了两个数据。首先是point_list。它的列表类型如下所示。

[1.0]
[3.0]
[0.0]
[2.0]
[1.0]

而另一个是addr_code。它还列出了如下数据类型。

['CA']
['NJ']
['DC']
['NJ']
['RI']

这两个数据显示了这些信息。 ' CA' = 1.0,' NJ' = 3.0,' DC' = 0.0,' NJ' = 2.0,' RI' = 1.0

从这些数据中,我想得到一个简单的结果,如下所示。

NJ has the biggest point: 5.0

如何编写代码以获得结果的最后一部分?请告诉我是否有错误的部分。 我等着你的帮忙。

4 个答案:

答案 0 :(得分:2)

使用collections.defaultdict

>>> lis2=['CA','NJ','DC','NJ','RI']
>>> lis1 =[1.0,3.0,0.0,2.0,1.0]
>>> from collections import defaultdict
>>> dic = defaultdict(float)
>>> for x,y in zip(lis2,lis1):
...     dic[x] += y
...     
>>> maxx = max(dic,key =dic.get)
>>> "{0} has the biggest point: {1}".format(maxx,dic[maxx])
'NJ has the biggest point: 5.0'

答案 1 :(得分:1)

import operator
l = [1.0,3.0,0.0,2.0,1.0]
f = ['CA', 'NJ', 'DC', 'NJ', 'RI', ]
d = dict()
for v, s in zip(l,f):
    if s not in d: d[s] = 0 
    d[s] += v
k=max(d.iteritems(), key=operator.itemgetter(1))[0]
print k, "has the biggest point:", d[k]

更新了您的问题:

d = dict()
with open("wordlist.txt") as f:
     for line in f:
        key, val = line.split("\t")
        key = key.sprip()
        if not key in d: d[key] = 0 
        d[key] += val 
k=max(d.iteritems(), key=operator.itemgetter(1))[0]
print k, "has the biggest point:", d[k]

答案 2 :(得分:1)

from collections import defaultdict
from operator import itemgetter
floats = [1.0,3.0,0.0,2.0,1.0]
labels = ['CA','NJ','DC','NJ','RI']

combined = defaultdict(float)
for (l,f) in zip(labels,floats):
    combined[l] += f
print("%s has the biggest point: %.1f" %max(combined.items(),key=itemgetter(1)))

可生产

>>> 
NJ has the biggest point: 5.0

答案 3 :(得分:0)

这与你上一个问题非常相似。当我在那里回答时,您可以使用dict.fromkeys将键设置为0:

point_list =[1.0,3.0,0.0,2.0,1.0]
addr_code= ['CA','NJ','DC','NJ','RI']

ans=dict.fromkeys(addr_code,0)
for k,v in zip(addr_code,point_list):
    ans[k]+=v

m=max(ans, key=lambda k: ans[k]) 
print('{} has the biggest point: {}'.format(m,ans[m]))

打印

NJ has the biggest point: 5.0
相关问题