Reputation: 215
Than I want to write a function that achieves this purpose, if given:
t = [1,2,[2,2],[3,3]]
I want a function that makes t be
[1,2,4,6]
. Here, is my code in Python:
t=[1,2,[2,2],[3,3]]
def nested_sum(t):
for x in t:
if type(t[x])=='int':
t[x]=t[x]
else:
t[x]=['sum(t[x])']
return t
nested_sum(t)
I got the error message that
Traceback (most recent call last):
File "nested_sum.py", line 11, in <module>
nested_sum(t)
File "nested_sum.py", line 5, in nested_sum
if type(t[x])=='int':
TypeError: list indices must be integers, not list
I am not quite sure about the mistake(s) I made. Since my logic is that:
type(t[0])=1
which is of "Int" type and type(t[2])=[2,2]
which is of "List" type and I think these fulfills the "if...else..." statement.
Any help would be appreciated for pointing my mistakes. Thank you so much in advance.
Upvotes: 0
Views: 446
Reputation: 5564
The problem with your code is that you are looping through the items of your list and not through the indexes. For making it work you should change your code like this:
def nested_sum(t):
for x in range(len(t)):
if type(t[x]) == int:
t[x] = t[x]
else:
t[x] = sum(t[x])
return t
Note also that int
in type(t[x]) == int
and sum(t[x])
in your else clause should not be strings.
Upvotes: 0
Reputation: 180512
You can put it in a single list comprehension using isinstance:
[sum(x) if isinstance(x,list) else x for x in t]
[1, 2, 4, 6]
You could use collection.Iterable which will work on any iterable like tuples etc..
t = [1,2,[2,2],[3,3],(4,5)]
from collections import Iterable
print [sum(x) if isinstance(x, Iterable) else x for x in t]
[1, 2, 4, 6, 9]
In the list comprehension, if x is an iterable/list we add the sum
of the subelements or else
we just take the element x
Using your own code, you would use enumerate to access the list elements using their index:
def nested_sum(t):
for ind, x in enumerate(t):
if type(t[ind])== int: # int not "int"
t[ind] = x
else:
t[ind] = sum(t[ind])
return t
In the code ind
is the index of each subelement and x
is the actual subelement
Upvotes: 4
Reputation: 4238
An answer would be:
def nested_sum(mixed_list):
res = list()
for element in mixed_list:
try:
a = sum(element)
except TypeError:
a = element
res.append(a)
return res
Which works fine if the list contains numbers and lists of numbers.
Upvotes: 0
Reputation: 712
def nested_sum(t):
for index, item in enumerate(t):
if type(item) == list:
t[index] = sum(item)
return t
Explanation:
enumerate(t)
returns (0, t[0]), (1, t[1]) etc.
Then, for each item
in t
, check if item
is a list
. If it is, replace it with the sum of all elements in that list. This is done in t[index] = sum(item)
.
Upvotes: 0
Reputation: 5193
Use sum() when x is a list, append it to res otherwise
t=[1,2,[2,2],[3,3]]
def nested_sum(l):
res = []
for x in l:
if type(x) == type([]):
res.append(sum(x))
elif type(x) == type(1):
res.append(x)
return res
nested_sum(t)
Upvotes: 0