I have a function that I'd like to iterate over a list of lists. The thing is, this list of lists is dynamic, meaning it changes based on user input.
Here is an example of my code:
result = func(5)
for z in Z[0]:
result += func(z)
where Z is the dynamic lists of lists and func is my function. The function should iterate over every element in the list subsetted list Z[0] and sum the results. The code works when the list of lists looks like this:
Z = [[1.1],[2.1],[3.1],[4.1]]
were Z[0] is just [1.1]. However sometimes this dynamic list of lists has more elements in each list, in which case i need to iterate over each element. Like below:
Z = [list([1.1, 1.3]),list([3.1]),list([4]])
in which case:
Z[0] = [list([1.1, 1.3])]
and my code should do the following:
result = func(5)
for z in Z[0]:
result += func(z)
....
func(1.1) + func(1.3)
When I try to run the code with the list of lists I get an error: "can only concatenate list (not "float") to list"
I'm sure it has something to do with trying to iterate over a list. If anyone has an easy fix to this, or knows the issue i'd love to know.
EDIT: I suppose my real issue is how these dynamic lists are being formed as pointed out by the answers below, I'll try to explain my issue a little further:
I'm using an answer here given by @Michael: Replacing certain elements of an array based on a given index
here is the code i use to produce the list of lists:
Arr1 = [9,7,3,1]
Arr2 = [[14,6],[13,2]]
Arr3 = [0,2]
Z = np.array([[Arr1[i]] if not np.sum(Arr3 == i) else Arr2[i] for i in np.arange(Arr1.size)], dtype=object)
Z = [[list([14, 6])], [list([7])], list[([13, 2])], list[([1])]]
Subsetting Z[0] results with
[list([14,6])]
which then gives me the error (can only concatenate list (not "float") to list) when i try to iterate .
When the condition i = Arr3 is not met (say Arr3 was empty) and it just reverts to the original array the output of this code gives:
Z = [[9][7][3][1]]
Z[0] = [9]
And with that the code to iterate over the list works. However I need to work for above as well.
IF I remove brackets from this line of code here:
Z = np.array([[Arr1[i]] if not np.sum(Arr3 == i) else Arr2[i] for i in np.arange(Arr1.size)], dtype=object)
remove brackets around [Arr1[i]]
--->
Z = np.array([Arr1[i] if not np.sum(Arr3 == i) else Arr2[i] for i in np.arange(Arr1.size)], dtype=object)
Then
Z = [list([14,6]),list([7]),list([13,2]),list([1])]
and
z[0] = [14,6]
and the code to iterate over the list works! But, then it does not work for the situation when the condition i = Arr 3 is not met, because the output looks like
[9 7 3 1]
Z[0] = 9
and I get the error 'float' object is not iterable.
Sorry that is a lot, but I think it explains my issue better. I'm unsure out to get the list formation correct for any situation.