How to flatten a list of nested tuples in Python? - python

I have a list of tuples that looks like this:
[('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
I want to turn it into this:
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]
What is the most Pythonic way to do this?

one-line, using list comprehension:
l = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
result = [z for y in (x if isinstance(x[0],tuple) else [x] for x in l) for z in y]
print(result)
yields:
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]
this is artificially creating a list if the element is not a tuple of tuples, then flattening all does the job. To avoid creating a single element list [x], (x for _ in range(1)) can also do the job (although it appears clunky)
Limitation: doesn't handle more than 1 level of nesting. In which case, a more complex/recursive solution must be coded (check Martijn's answer).

Adjust the canonical un-flatten recipe to only unflatten when there are tuples in the value:
def flatten(l):
for el in l:
if isinstance(el, tuple) and any(isinstance(sub, tuple) for sub in el):
for sub in flatten(el):
yield sub
else:
yield el
This will only unwrap tuples, and only if there are other tuples in it:
>>> sample = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
>>> list(flatten(sample))
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]

A one-line solution would be using itertools.chain:
>>> l = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
>>> from itertools import chain
>>> [*chain.from_iterable(x if isinstance(x[0], tuple) else [x] for x in l)]
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]

Related

Loop over list of strings in python

I have a list l of stings from a to z generated by using l=list(string.ascii_lowercase).
I want to take one value from the list l and combine with all other values of list except that selected value. For eg. ab,ac.....az.
Again take b and combine with all other values like ba,bb.....bz.
I know there will be redundant combinations.
I have tried this
for i in range(0, len(l)):
for j in range(0,len(l.pop(i))):
print (l[i],l[j])
I am getting 'list index out of range' error.
Is there more optimized way of doing it ?
In [1]: import string, itertools
In [2]: combinations = list(itertools.combinations(string.ascii_lowercase, 2))
In [4]: combinations
Out[4]:
[('a', 'b'),
('a', 'c'),
('a', 'd'),
('a', 'e'),
('a', 'f'),
('a', 'g'),
('a', 'h'),
('a', 'i'),
('a', 'j'),
('a', 'k'),
('a', 'l'),
('a', 'm'),
('a', 'n'),
('a', 'o'),
('a', 'p'),
...]
mylist = list(string.ascii_lowercase)
selected_value = 'b'
new_list = [selected_value+i for i in mylist if i != selected_value]

Get all combinations of a list in Python [duplicate]

This question already has answers here:
How to calculate a Cartesian product of a list with itself [duplicate]
(2 answers)
Closed 2 years ago.
I would like to get all combinations of a list:
L = ["a","b","c"]
combinations(L,length=2)
# [("a","a"),("a","b"),("a","c"),("b","a"),("b","b"),("b","c"),("c","a"),("c","b"),("c","c")]
I've tried
itertools.combinations()
but this returned
[('a', 'b'), ('a', 'c'), ('b', 'c')]
When I use itertools.permutations(), it just returns the combinations with the length of the iteration, which is also not what I want.
Any librarys / function that I can use, without writing my own?
You can use itertools.product with repeat=2 like so:
from itertools import product
L = ["a","b","c"]
print(list(product(L, repeat=2)))
#[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
A simple list comprehesion can do the job too.
L = ["a","b","c"]
print([(a,b) for a in L for b in L])
#[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
The product function from itertools offers a solution.
In [17]: from itertools import product
In [18]: L = ["a","b","c"]
In [19]: list(product(L, L))
Out[19]:
[('a', 'a'),
('a', 'b'),
('a', 'c'),
('b', 'a'),
('b', 'b'),
('b', 'c'),
('c', 'a'),
('c', 'b'),
('c', 'c')]
itertools module has a function called product which is what you are looking for.
>>> L = ["a", "b", "c"]
>>> list(itertools.product(L, repeat=2))
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
You can use the second parameter of itertools.permutations():
from itertools import permutations
L = ["a","b","c"]
print([n for n in permutations(L,2)]+[(i,i) for i in L])
Output:
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('a', 'a'), ('b', 'b'), ('c', 'c')]
From the documentation:
itertools.permutations(iterable, r=None)
Return successive r length permutations of elements in the iterable.
If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.

Python - Removing tuples by prefix and suffix from list

What's the fastest way to remove tuples from a python list (and update the list with the removed tuples) according to what the tuple starts with or ends with.
Example:
import itertools
l1 = ["a", "b", "c"]
l2 = ["d", "e", "f"]
tupl_lst = list(itertools.product(l1, l2))
tupl_lst
Out[42]:
[('a', 'd'),
('a', 'e'),
('a', 'f'),
('b', 'd'),
('b', 'e'),
('b', 'f'),
('c', 'd'),
('c', 'e'),
('c', 'f')]
I want to remove all tuples that starts with 'a' OR ends with 'f' so that my output will look as follows:
[('b', 'd'),
('b', 'e'),
('c', 'd'),
('c', 'e')]
What is the fastest way to do it ?
You can even skip the itertools.product()and just use one list-comprehension:
l1 = ["a", "b", "c"]
l2 = ["d", "e", "f"]
tupl_lst = [(x, y) for x in l1 for y in l2 if x!="a" and y!="f"]
#output
[('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e')]
with a list comprehension:
[t for t in tupl_lst if t[0]!='a' and t[1]!='f']
with filter:
list(filter(lambda t: t[0]!='a' and t[1]!='f',tupl_lst))
Avoid the prefix (a) and suffix (f) altogether by iterating over slices of the lists.
[(x, y) for x in l1[1:] for y in l2[:-1]]
# [('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e')]

Find all unique pairs of keys of a dictionary

If there's a dictionary:
test_dict = { 'a':1,'b':2,'c':3,'d':4}
I want to find pairs of keys in list of tuples like:
[('a','b'),('a','c'),('a','d'),('b','c'),('b','d'),('c','d')]
I tried with the following double iteration
test_dict = { 'a':1,'b':2,'c':3,'d':4}
result = []
for first_key in test_dict:
for second_key in test_dict:
if first_key != second_key:
pair = (first_key,second_key)
result.append(pair)
But it's generating the following result
[('a', 'c'), ('a', 'b'), ('a', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('d', 'a'), ('d', 'c'), ('d', 'b')]
For my test case ('a','b') and ('b','a') are similar and I just want one of them in the list. I had to run one more loop for getting the unique pairs from the result.
So is there any efficient way to do it in Python (preferably in 2.x)? I want to remove nested loops.
Update:
I have checked with the possible flagged duplicate, but it's not solving the problem here. It's just providing different combination. I just need the pairs of 2. For that question a tuple of ('a','b','c') and ('a','b','c','d') are valid, but for me they are not. I hope, this explains the difference.
Sounds like a job for itertools.
from itertools import combinations
test_dict = {'a':1, 'b':2, 'c':3, 'd':4}
results = list(combinations(test_dict, 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
I should add that although the output above happens to be sorted, this is not guaranteed. If order is important, you can instead use:
results = sorted(combinations(test_dict, 2))
Since dictionary keys are unique, this problem becomes equivalent of finding all combinations of the keys of size 2. You can just use itertools for that:
>>> test_dict = { 'a':1,'b':2,'c':3,'d':4}
>>> import itertools
>>> list(itertools.combinations(test_dict, 2))
[('c', 'a'), ('c', 'd'), ('c', 'b'), ('a', 'd'), ('a', 'b'), ('d', 'b')]
Note, these will come in no particular order, since dict objects are inherently unordered. But you can sort before or after, if you want sorted order:
>>> list(itertools.combinations(sorted(test_dict), 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>>
Note, this algorithm is relatively simple if you are working with sequences like a list:
>>> ks = list(test_dict)
>>> for i, a in enumerate(ks):
... for b in ks[i+1:]: # this is the important bit
... print(a, b)
...
c a
c d
c b
a d
a b
d b
Or more succinctly:
>>> [(a,b) for i, a in enumerate(ks) for b in ks[i+1:]]
[('c', 'a'), ('c', 'd'), ('c', 'b'), ('a', 'd'), ('a', 'b'), ('d', 'b')]
>>>
itertools.combinations does just what you want:
from itertools import combinations
test_dict = { 'a':1,'b':2,'c':3,'d':4}
keys = tuple(test_dict)
combs = list(combinations(keys, 2))
print(combs)
# [('a', 'd'), ('a', 'b'), ('a', 'c'), ('d', 'b'), ('d', 'c'), ('b', 'c')]
combs = list(combinations(test_dict, 2)) would just do; iterating over a dictionary is just iterating over its keys...

python itertools.combinations deleted

I've noticed that the itertools.combinations object in Python can seemingly delete itself:
>>> import itertools
>>> x = itertools.combinations( 'ABCD', 2 )
>>> print list( x )
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
>>> print list( x )
[]
Why has the object x changed here? I haven't assigned x to be anything.
You are creating an generator. If you want to use the values later on save them to a list:
>>> import itertools
>>> x = itertools.combinations( 'ABCD', 2 )
>>> list_of_x = list( x )
>>> print(list_of_x)
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
>>> print(list_of_x)
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
itertools.combinations (along with many of the other itertools methods) return a generator expression. Generators can only be read exactly 1 time.
You can read more about generators here
Iterator works just once.
You can't use iterator object again.
Iterator works as generators including next() function and raise Stop Iteration error,
you can read about it here

Categories