Python Forum

Full Version: Make Groups with the List Elements
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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
(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