Python Forum
Make Groups with the List Elements - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Make Groups with the List Elements (/thread-34249.html)



Make Groups with the List Elements - quest - Jul-11-2021

Hello,

I have pairs list:
pairs=[[A,B],[C,D],[Z,X]]
And I have also a queue list which is includes:
queue =[A,B,C,D,E,F,G,H,I,Z,X,J,K,L]
And I want to make groups from list queue and this groups should be exactly the same with elements of pairs. I mean, I want to make [A,B] [C,D] [Z,X] groups if these elements[A,B,C,DZ,X] exist inside the queue list.
Note: here A,B,C,D,Z,X are just an example. In my code they correspond objects

How can I do that?


RE: Make Groups with the List Elements - Yoriz - Jul-11-2021

loop over the pairs, check if both pair items are in the list of queue items, if they are add the pair to a new list


RE: Make Groups with the List Elements - perfringo - Jul-11-2021

(Jul-11-2021, 08:35 AM)quest Wrote: How can I do that?

Figuring out solution and writing code.

Lot of ambiguity in problem description, but there is data structure in Python called sets which primary purpose is:

Quote:A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

So one can write something like that:

>>> names = ['spam', 'ham', 'eggs', 'bacon']
>>> pairs = [['ham', 'bacon'], ['spam', 'foo']]
>>> for pair in pairs:
...     print(set(pair).issubset(names))
...
True
False