python 如何合并嵌套列表中的元素并改变内部元素?

isr3a4wc  于 2023-04-04  发布在  Python
关注(0)|答案(3)|浏览(149)

我有一个嵌套的列表。两个内部元素可以是相同的,一个是不同的。我需要以某种方式改变列表,以更好地演示。

before = [['a','a', 1],['a','a', 2], ['a','b', 6], ['a','b', 0], ['a','c',5]
#after some changes
after = [['a','a', 3], ['a','b', 6], ['a','c',5]]

所以我需要总结“i[2]元素for i in before”,如果i[0],i[1]是相同的。这个公式已经看起来像是理解了,但是我看不出有什么方法可以这样做。
我就是这么做的。但我肯定这不是最好的解决办法。

before = [['a','a', 1],['a','a', 2], ['a','b', 6], ['a','b', 0], ['a','c',5]]
#creating a list of unique combinations, actually it's already created and used for another aims too
after = set([(i[0],i[1],0) for i in before])
after = [list(i) for i in after]
# output is [['a', 'c', 0], ['a', 'b', 0], ['a', 'a', 0]]

for k,i in enumerate(after):
    #starting the loop from list of uniq_combinations
    q = 0 #for element we need to summarize, reseting var for each iteration
    for j in before:
            if (i[0],i[1]) == (j[0],j[1]):
                q = j[2] #the third element for each nested list
                after[k][2] +=q #summarizing the result while looking for same combination
print(after)
#output have correct result [['a', 'a', 3], ['a', 'b', 6], ['a', 'c', 5]]

我在itertools库中找过,但找不到合适的方法

wgmfuz8q

wgmfuz8q1#

可以使用itertools.groupby,只要具有相同键的元素总是相邻的。

from itertools import groupby
l = [['a','a', 1],['a','a', 2], ['a','b', 6], ['a','b', 0], ['a','c',5]]
res = [[*k, sum(o[2] for o in g)] for k, g in groupby(l, lambda o:o[:2])]

defaultdict也可以用来存储每个键的和。

from collections import defaultdict
d = defaultdict(int)
for *k, v in l: d[tuple(k)] += v
res = [[*k, v] for k, v in d.items()]
gdx19jrr

gdx19jrr2#

只需跟踪字典中每对字符的当前计数。当您迭代before列表中的item s时,检索字典中item[0:2]处的值,并将item[2]添加到此值。

result = {}
for item in before:
    # Convert item[0:2] to tuple because dict keys need to be immutable
    key = tuple(item[0:2]) 

    # Get value in result at key (or zero if it doesn't exist)
    # Then add item[2] to it
    # Then assign it back to result[key]
    result[key] = result.get(key, 0) + item[2]

这使得result为:

{('a', 'a'): 3, ('a', 'b'): 6, ('a', 'c'): 5}

现在,只需迭代result的键和值,并创建after列表:

after = [[*key, val] for key, val in result.items()]

其给出:

[['a', 'a', 3], ['a', 'b', 6], ['a', 'c', 5]]
idfiyjo8

idfiyjo83#

Pranav Hosangadi使用的方法几乎相同。
我们迭代列表并创建一个字典,其键是前两个元素作为元组,值是第三个坐标的和。我们不必手动添加:collections.Counter可以为我们做到这一点:

from collections import Counter

before_counter = Counter()
for triad in before:
    # Tuple as a key, third element as the quantity
    before_counter.update({(triad[0], triad[1]) : triad[2]})

然后将其转换为所需的列表:

after = [[*pair, count] for pair, count in before_counter.items()]

相关问题