Multi-List to an order dictionary by different column - python-3.x

I have a OrderedDict below, which column1 and column2 present a relationship
This created for me the following OrderedList
OrderedDict([('AD',
[['A', 'Q_30', 100],
['A', 'Q_24', 74],
['B', 'Q_28', 37],
['B', 'Q_30', 100],
['C', 'Q_25', 38],
['C', 'Q_30', 100],
['D', 'D_4', 44],
['E', 'D_4', 44],
['F', 'D_5', 44]])
I would like to iterate over the elements, each time look at other row and collect column2.
eg.
element A contain Q_30 and Q24 and collect related member from other rows
element B contain Q_30, so collect Q24,Q28,Q30 and order by column3
OrderedDict([('AD',
[{'Q_30':100, 'Q_24':74, 'Q_25':38, 'Q_28': 37}, {'D_4':44}, {'D_5':44}])

When I understand this correctly, your "OrderedDict" is currently a tuple with a list inside, in which is another list and is meant to look like this:
OrderedList = ('AD',
[['A', 'Q_30', 100],
['A', 'Q_24', 74],
['B', 'Q_28', 37],
['B', 'Q_30', 100],
['C', 'Q_25', 38],
['C', 'Q_30', 100],
['D', 'D_4', 44],
['E', 'D_4', 44],
['F', 'D_5', 44]])
and you want to convert it into a tuple with a list inside which holds dicts:
OrderedDict = ('AD',
[{'Q_30': 100,
'Q_24': 74,
'Q_25': 38,
'Q_28': 37},
{'D_4': 44},
{'D_5': 44}])
In this case I am guessing you look for groupby():
from itertools import groupby
OrderedList = ('AD',
[['A', 'Q_30', 100],
['A', 'Q_24', 74],
['B', 'Q_28', 37],
['B', 'Q_30', 100],
['C', 'Q_25', 38],
['C', 'Q_30', 100],
['D', 'D_4', 44],
['E', 'D_4', 44],
['F', 'D_5', 44]])
for key, group in groupby(OrderedList[1], lambda x: x[0]):
for thing in group:
print("%s is a %s." % (thing[1], key))
Gives:
Q_30 is a A.
Q_24 is a A.
Q_28 is a B.
Q_30 is a B.
Q_25 is a C.
Q_30 is a C.
D_4 is a D.
D_4 is a E.
D_5 is a F.
This is not the full answer, but an example as I feel like it would be spoon-feeding otherwise

Related

Make a list inside the dictionary in python

I have a data frame like below. I want to get a dictionary consisting of a list.My expected output is. Can you pls assist me to get it?
You can use the handy groupby function in Pandas:
df = pd.DataFrame({
'Department': ['y1', 'y1', 'y1', 'y2', 'y2', 'y2'],
'Section': ['A', 'B', 'C', 'A', 'B', 'C'],
'Cost': [10, 20, 30, 40, 50, 60]
})
output = {dept: group['Cost'].tolist() for dept, group in df.groupby('Department')}
gives
{'y1': [10, 20, 30], 'y2': [40, 50, 60]}

How do I order double list of elements of this type: [[1,2,3], [a,b,c]]?

I have a double list of this type: dl = [[13, 22, 41], ['c', 'b', 'a']], in which, each element dl[0][i] belongs a value in dl[1][i] (with the same index). How can I sort my list using dl[0] values as my order criteria, maintainning linked both sublists? Sublist are kind of 'linked data', so the previous dl[0][i] and dl[1][i] values must match their index after sorting the parent entire list, using as sorting criteria, the first sublist values
I expect something like:
input: dl = [ [14,22,7,17], ['K', 'M', 'F','A'] ]
output: dl = [ [7, 14, 17, 22], ['F', 'K', 'A', 'M'] ]
This was way too much fun to write. I don't doubt that this function can be greatly improved, but this is what I've gotten in a very short amount of time and should get you started.
I've included some tests just so you can verify that this does indeed do what you want.
from unittest import TestCase, main
def sort_by_first(data):
sorted_data = []
for seq in data:
zipped_to_first = zip(data[0], seq)
sorted_by_first = sorted(zipped_to_first)
unzipped_data = zip(*sorted_by_first)
sorted_data.append(list(tuple(unzipped_data)[1]))
return sorted_data
class SortByFirstTestCase(TestCase):
def test_sort(self):
output_1 = sort_by_first([[1, 3, 5, 2, 4], ['a', 'b', 'c', 'd', 'e']])
self.assertEqual(output_1, [[1, 2, 3, 4, 5], ['a', 'd', 'b', 'e', 'c']])
output_2 = sort_by_first([[9, 1, 5], [21, 22, 23], ['spam', 'foo', 'bar']])
self.assertEqual(output_2, [[1, 5, 9], [22, 23, 21], ['foo', 'bar', 'spam']])
if __name__ == '__main__':
main()
Updated for what you're looking for, selection sort but added another line to switch for the second list to match the first.
for i in range(len(dl[0])):
min_idx = i
for j in range(i+1, len(dl[0])):
if dl[0][min_idx] > dl[0][j]:
min_idx = j
dl[0][i], dl[0][min_idx] = dl[0][min_idx], dl[0][i]
dl[1][i], dl[1][min_idx] = dl[1][min_idx], dl[1][i]
You can try solving this with a for loop also:
dl = [ [3,2,1], ['c', 'b', 'a'] ]
for i in range(0,len(dl)):
dl[i].sort()
print(dl)

Extract longest common path between two lists in python

Lets say there are two lists
L1=[['A', ['C', ['B', ['D', 0]]]],
[['A', ['D', ['K', ['C', ['E', 0]]]]],
[['A', ['C', ['B', ['M', 0]]]]]
and
L2=[['A', ['C', ['B', ['K', 0]]]],
[['A', ['C', ['B', ['B', ['E', 0]]]]],
[['A', ['D', ['K', ['F', 0]]]]]
Then the output should return all the sub-paths with longest common path. For example:
Since 'A', 'C', 'B' is common L1 and L2; output should be:
[['A', ['C', ['B', ['D', 0]]]],
[['A', ['C', ['B', ['M', 0]]]],
[['A', ['C', ['B', ['K', 0]]]],
[['A', ['C', ['B', ['B', ['E', 0]]]]]
. Also, 'A', 'D', 'K' is also common for one time in L1 and L2; the output whould be:
[['A', ['D', ['K', ['C', ['E', 0]]]]],
[['A', ['D', ['K', ['F', 0]]]]]
I tried :
[i for i in L1 if i in L2]
but it will give the output of all the common paths till the leaf (end).
take something from the great and marvelous c!
you can simply use a while in another and check letter by letter, if one is different exit the first while and put the character to 0
like
while (var[i][n] && var2[i][n])
while (var[i][n] == var2[i][n])
n = n + 1
var[i][n] = 0
or something like that.
but it is not really optimised.

How to filter similar edges in a list?

I have a list which contains all the edges of an undirected weighted graph.I further sorted it in increasing order of their edge weights.
The list is as follows
lis = [['B', 'C', 1], ['C', 'B', 1], ['B', 'A', 2], ['C', 'A', 2], ['A', 'C', 2], ['A', 'B', 2], ['D', 'C', 3], ['C', 'D', 3], ['B', 'D', 5], ['D', 'B', 5]]
Now in the list, ['B', 'C', 1], ['C', 'B', 1] means the same thing.That is an edge BC has a weight of 1 and edge CB has a weight of 1.Similarly we have edges AB, BA and so on in the list.
How do I keep only one of the two edges and not both since they both mean the same thing.So for ['B', 'C', 1], ['C', 'B', 1], I only want to keep say ['B', 'C', 1].How do I do that?
I found a similar question but I am not really sure how to implement it in my case.
Removing duplicate edges from graph in Python list
I tried to implement the solution posted in the link for my situtation but doesn't work
def normalize(t):
[n1, n2, dist] = t
if n1 < n2:
return t
else:
return [n2, n1, dist]
unique_edges = set(map(normalize, lis))
Simply sort each item and remove duplicates:
>>> lis = sorted([sorted(item) for item in lis])
>>> [lis[i][::-1] for i in range(len(lis)) if i == 0 or lis[i] != lis[i-1]]
[['C', 'B', 1], ['B', 'A', 2], ['C', 'A', 2], ['D', 'C', 3], ['D', 'B', 5]]

node.js: using foreach with a multidimensional array

im trying to call a function with every line of an array which is an array itself. So far I always get an error with my code, which I cant seem to straighten out. Can someone tell me how to do it right?
The output should be "['a', 4], ['b', 1], ['j', 2], ['c', 3], ['d', 5], ['e', 2], ['f', 2], ['g', 6]".
var testqueue = [['a', 4], ['b', 1], ['j', 2], ['c', 3], ['d', 5], ['e', 2], ['f', 2], ['g', 6]];
function test(cb){
testqueue.foreach(function(item){
console.log(item);
});
cb('done');
}
test(function(result){
console.log(result);
});
Sorry it was only a typo :(
it should be forEach (capital E) and everything works fine.

Resources