在python中计算列表中的元素

2024-10-01 15:39:41 发布

您现在位置:Python中文网/ 问答频道 /正文

希望你能帮助我使用这个python函数:

def comparapal(lista):#lista is a list of lists where each list has 4 elements
  listaPalabras=[]
  for item in lista:
     if item[2] in eagles_dict.keys():# filter the list if the 3rd element corresponds to the key in the dictionary
        listaPalabras.append([item[1],item[2]]) #create a new list with elements 2 and 3

listaPalabras结果:

^{pr2}$

我的问题是:如何比较每个列表的第一个元素,以便如果单词是相同的,则比较它们的第二个元素标记。在

很抱歉模棱两可,fufunction必须返回一个包含3个元素的列表列表:单词、标记和每个单词的出现次数。但是为了计算单词数,我需要比较单词w/others,如果有两个或两个以上的单词相似,那么将标签与chk进行比较。如果标记不同,则分别计算单词数。在

result->;[['bien','NP00000',1],['bien','RG',1]]->;两个相同的单词,但通过比较标记分别计算 提前感谢:


Tags: the函数in标记gt元素列表if
3条回答

当然,完全基于列表的解决方案是可能的,但需要额外的循环。如果效率很重要,最好用dict代替listaPalabras

def comparapal(lista):
  listaPalabras=[]
  for item in lista:
     if item[2] in eagles_dict.keys():
        listaPalabras.append([item[1],item[2]])

  last_tt = [None, None]
  for tt in sorted(listaPalabras):
    if tt == last_tt:
      print "Observed %s twice" % tt
    elif tt[0] == last_tt[0]:
      print "Observed %s and %s" % (tt, last_tt)
    last_tt = tt

这将为您提供: Observed ['bien', 'RG'] and ['bien', 'NP00000']

如果这不符合您的目的,请说明您的问题。在

你需要什么具体的输出?我不知道你到底需要做什么,但如果你想把同一个单词相关的条目分组,你可以把这个结构转换成字典,以后再操作它

>>> new = {}
>>> for i,j in a: # <  a = listaPalabras 
        if new.get(i) == None:
                new[i] = [j]
        else:
                new[i].append(j)

这将给我们:

^{pr2}$

以后你可以:

>>> for i in new:
        if len(new[i]) > 1:
                print "compare {this} and {that}".format(this=new[i][0],that=new[i][1])

将打印:

compare NP00000 and RG #for key bien

编辑: 在第一步中,还可以使用defaultdict,正如Marcin在评论中建议的那样,如下所示:

>>> d = defaultdict(list)
>>> for i,j in a:
        d.setdefault(i,[]).append(j)

EDIT2(对OP评论的回答)

for i in d:
    item = []
    item.append(i)
    item.extend(d[i])
    item.append(len(d[i]))
    result.append(item)

这给了我们:

[['francisco', 'NP00000', 1], ['ser', 'VSIS3S0', 1], ['cosa', 'NCFS000', 1], ['ya', 'RG', 1], ['bien', 'NP00000', 'RG', 2], ['estar', 'VAIP1S0', 1], ['calcio', 'NCMS000', 1], ['leche', 'NCFS000', 1], ['huevo', 'NCMS000', 1], ['gracia', 'NCFP000', 1], ['proteina', 'NCFS000', 1]]
import collections
inlist = [
   ['bien', 'NP00000'],
   ['gracia', 'NCFP000'],
   ['estar', 'VAIP1S0'],
   ['bien', 'RG'],
   ['huevo', 'NCMS000'],
   ['calcio', 'NCMS000'],
   ['leche', 'NCFS000'],
   ['proteina', 'NCFS000'],
   ['francisco', 'NP00000'],
   ['ya', 'RG'],
   ['ser', 'VSIS3S0'],
   ['cosa', 'NCFS000']
]
[(a,b,v) for (a,b),v in collections.Counter(map(tuple,inlist)).iteritems()]
#=>[('proteina', 'NCFS000', 1), ('francisco', 'NP00000', 1), ('ser', 'VSIS3S0', 1), ('bien', 'NP00000', 1), ('calcio', 'NCMS000', 1), ('estar', 'VAIP1S0', 1), ('huevo', 'NCMS000', 1), ('gracia', 'NCFP000', 1), ('bien', 'RG', 1), ('cosa', 'NCFS000', 1), ('ya', 'RG', 1), ('leche', 'NCFS000', 1)]

您需要计算每对出现的次数。counter表达式可以做到这一点。列表理解将其格式化为三倍。在

相关问题 更多 >

    热门问题