Reputation: 35
I want to append the values of the specific indices of a nested list based on the values of the same list but on different indices.
So, basically, if my initial list looks like the following:
a = [(1,2,1,[1,2,3]) , (1,2,2,[3,2,4]) , (1,2,3,[7,3,4]) , (1,2,3,[11,2,7]) ,..., (2,1,1,[5,6,3]) , (2,1,2,[3,1,8]) , ...]
I would like to firstly have a list of all the values of the 3rd index of the list a, which share the same value of the 1st and 2nd index in the list a. So, the 1st output will look like the following:
b = [[1,2,3] , [3,2,4] , [7,3,4] , [11,2,7]]
Then, I would like to run some calculations on the output, save the data and get the other set of data that share the same value of the 1st and 2nd index from the initial list (list a).
This process should be repeated for all the values of the initial list, till there is non left in that list.
With the following code, I get the 1st set of data, but I face problems to get the next set:
od = 1
ri = 1
q=0
for i in range(len(a)):
while q<len(a):
if a[q][0]==od and a[q][1]==ri:
b.append(Net_info[q][3])
q+=1
ri += 1
od += 1
Upvotes: 0
Views: 120
Reputation: 1493
>>> data = dict()
>>> a = [(1, 2, 1, [1, 2, 3]), (1, 2, 2, [3, 2, 4]), (1, 2, 3, [7, 3, 4]), (1, 2, 3, [11, 2, 7]), (2, 1, 1, [5, 6, 3]), (2, 1, 2, [3, 1, 8])]
>>> for d in a:
... data.setdefault(d[:2], []).append(d[3])
>>> data
{(1, 2): [[1, 2, 3], [3, 2, 4], [7, 3, 4], [11, 2, 7]], (2, 1): [[5, 6, 3], [3, 1, 8]]}
>>> output = data.values()
[[[5, 6, 3], [3, 1, 8]], [[1, 2, 3], [3, 2, 4], [7, 3, 4], [11, 2, 7]]]
try this snippet, hope this helps
Upvotes: 2
Reputation: 476544
Simply use a defaultdict
and append the third element based on the first two elements, like:
from collections import defaultdict
result = defaultdict(list)
for ai in a:
result[ai[:2]].append(ai[3])
This generates a dictionary like:
>>> result
defaultdict(<class 'list'>, {(1, 2): [[1, 2, 3], [3, 2, 4], [7, 3, 4], [11, 2, 7]], (2, 1): [[5, 6, 3], [3, 1, 8]]})
So a dictionary that maps the first two elements of the tuple onto a list of those elements associated with index three.
Now we can process these lists individually, like:
for k,b in result.items():
print('%s: %s'%(k,b))
This generates:
>>> for k,b in result.items():
... print('%s: %s'%(k,b))
...
(1, 2): [[1, 2, 3], [3, 2, 4], [7, 3, 4], [11, 2, 7]]
(2, 1): [[5, 6, 3], [3, 1, 8]]
This algorithm will perform a single pass over a
. And will not look for configurations of the first two items of tuples that are nowhere to be found in a
.
Upvotes: 5