Python在tuple列表中组合int的值。

问题描述 投票:1回答:1

我有一个数据列表结构,看起来像这样。

[(a, 1),(a, 2),(b, 0),(b, 1),(c, 0)]

如果第一项是相同的,我就想把第二项的值合并起来 (并删除重复的内容)

最终结果应该是:

[(a, 3),(b, 1),(c, 0)]

我的方法是创建第二个空列表 检查第一个元素是否存在于列表中 如果不存在,则进行追加 否则在第二个列表中循环,并将第一个列表中迭代的[1]项的值添加到第二个列表中的[1]项中。我无法让我的概念工作。如果有人有更有效的解决方案,我也愿意接受建议。

secondList = []
for item in firstList:
    if (secondList.count(item[0]]):
      secondList.append(item)
    else:
      for item_j in secondList:
        if (item_j[0] == item[0]):
          item_j[1] = item_j[1]+item[1]

我将非常感激您的帮助。谢谢你的帮助。

python list algorithm int tuples
1个回答
1
投票

你可以使用一个字典来获得所需的结果,而不需要导入任何额外的模块。

lst = [('a', 1),('a', 2),('b', 0),('b', 1),('c', 0)]

Dict = {}

for tup in lst:

    first=tup[0]
    second=tup[1]
    if first not in Dict:
        Dict[first]=0
    Dict[first]+=second

secondList = []

for key in Dict.keys():
    secondList.append((key,Dict[key]))

print(secondList)

4
投票

你可以使用 itertools.groupby. 首先将它们按0号指数进行分组,然后对每组进行 sum 第1个指数的值。

from itertools import groupby
from operator import itemgetter
data = [("a", 1),("a", 2),("b", 0),("b", 1),("c", 0)]

result = [(k, sum(item[1] for item in g)) for k, g in groupby(data, key=itemgetter(0))]
print(result)

输出。

[('a', 3), ('b', 1), ('c', 0)]

P.S.: 请注意,如果你的列表没有像文档中说的那样,在第0个索引上进行排序的话,这不会像你所期望的那样工作。

一般来说,iterable需要在同一个键函数上进行排序。


1
投票

这对于字典来说似乎是一个很好的案例。对于列表,你必须在列表中搜索,才能找到你所引用的项目。O(n). 有了字典,搜索时间是 O(1).

tuple_dict = {}
for item in firstList:
  key,value = item
  if key in tuple_dict:
    tuple_dict[key]+=value
  else:
    tuple_dict[key]=value

然后,如果你想的话,你可以把它转换回你的元组列表。

tuple_list = []
for key,value in tuple_dict.items():
  tuple_list.append((key,value))

1
投票

现有的答案很好,这里还有一种方法,你可以用一个 defaultdict:

from collections import defaultdict

def sum_tuples(tuples):
    result = defaultdict(int)
    for i in tuples:
        result[i[0]] += i[1]
    return [(k, result[k]) for k in result.keys()]

0
投票

将pandas作为pd导入

data = [("a", 1),("a", 2),("b", 0),("b", 1),("c", 0)]

df = pd.DataFrame( data , columns=['c1','c2'])

x = tuple ( df.groupby( 'c1' ).sum().to_dict()['c2'].items() ) )

打印(x)

© www.soinside.com 2019 - 2024. All rights reserved.