Home > other >  Adding an element in a nested list based on condition
Adding an element in a nested list based on condition

Time:05-03

I was wondering if you could help me simplify my code or find an efficient method. I am given a nested array and I wish to add the second element based on the first nested item.

[('dog','1'),('dog','2'),('cat',1'),('cat','2')]

This will result in:

[('dog','3'),('cat','3')]

I would want the numbers to be strings instead of int type. Here is my code below:

dddd=[]
        dddd=result_1_ce result_2_ce result_3_ce result_4_ce
#Sum all of the elements from a prior find dddd stores [('dog','1'),('dog','2'),('cat',1'),('cat','2')]

        newlist = [[int(element) if element.isdigit() else element for element in sub] for sub in dddd]
        
        grouped = dict()
        grouped.update((name,grouped.get(name,0) value) for name,value in newlist)
        dddd = [*map(list,grouped.items())]

#Of this manipulation display it in reverse order
        dddd=sorted(dddd,key=lambda x:x[1],reverse=True)
        X = [tuple(i) for i in dddd]
        print("Findings:",X)

CodePudding user response:

This code work

I am writing a comment where I change the code.

dddd=result_1_ce result_2_ce result_3_ce result_4_ce

#Sum all of the elements from a prior find dddd stores [('dog','1'),('dog','2'),('cat',1'),('cat','2')]

newlist = [[int(element) if element.isdigit() else element for element in sub] for sub in dddd]

grouped = dict()
grouped.update((name,grouped.get(name,0) value) for name,value in newlist)
dddd = [*map(list,grouped.items())]

#Of this manipulation display it in reverse order
dddd=sorted(dddd,key=lambda x:x[1],reverse=True)
X = [tuple([f,str(s)]) for f,s in dddd]  # get two both element from the list of list and change second('s) element to str.
print("Findings:",X)

OUTPUT

Findings: [('dog', '3'), ('cat', '3')]

You dddd list is looks like this [['dog', 3], ['cat', 3]].

# If I write This

dddd = [['dog', 3], ['cat', 3]]

for f,s in dddd: # (f is for 'dog' and 'cat) and (s is for 3 and 3)
    print(f)
    print(s)

CodePudding user response:

It seems to me, a very simple approach would be to convert to a dictionary first, and it is a good data structure for grouping. Also, use an integer to sum the numbers. You can use int of str if you are unsure if each number value will be int or str. Then to get the output of list of tuples, you just convert with a simple comprehension.

l = [("dog", "1"), ("dog", "2"), ("cat", 1), ("cat", "2")]
d = {}
for t in l:
    d[t[0]] = d.setdefault(t[0], 0)   int(str(t[1]))

print([(k, str(v)) for k, v in d.items()])

Output:

[('dog', '3'), ('cat', '3')]
  • Related