I am kind of new to python and currently struggling with returning the list of tuples in a way I want to.
If I have a list of tuples that looks like
[('a',),('b',),('c',),('d',),('e',),('f',)]
How can I change it to
[('a','b'),('c','d'),('e','f')]
or
[('a','b','c'),('d','e'),('f',)] ?
Is there an easy way to regroup tuples?
Any help would be appreciated.
For a consistent length of inner tuples, you can flatten your list of tuples via itertools.chain and then define a chunking generator:
from itertools import chain
L = [('a',),('b',),('c',),('d',),('e',),('f',)]
def chunker(L, n):
T = tuple(chain.from_iterable(L))
for i in range(0, len(L), n):
yield T[i: i+n]
res_2 = list(chunker(L, 2)) # [('a', 'b'), ('c', 'd'), ('e', 'f')]
res_3 = list(chunker(L, 3)) # [('a', 'b', 'c'), ('d', 'e', 'f')]
res_4 = list(chunker(L, 4)) # [('a', 'b', 'c', 'd'), ('e', 'f')]
Otherwise, you need to first define logic to determine the size of each tuple.
You could use zip with appropriate slices:
l = [('a',),('b',),('c',),('d',),('e',),('f',)]
[x+y for x, y in zip(l[::2], l[1::2])]
# [('a', 'b'), ('c', 'd'), ('e', 'f')]
Use grouper from itertools recipe:
from itertools import chain, zip_longest
lst = [('a',),('b',),('c',),('d',),('e',),('f',)]
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
How to use?
>>> list(grouper(2, chain.from_iterable(lst)))
[('a', 'b'), ('c', 'd'), ('e', 'f')]
>>> list(grouper(3, chain.from_iterable(lst)))
[('a', 'b', 'c'), ('d', 'e', 'f')]
Related
I have a list like this
attach=['a','b','c','d','e','f','g','k']
I wanna pair each two elements that followed by each other:
lis2 = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'k')]
I did the following:
Category=[]
for i in range(len(attach)):
if i+1< len(attach):
Category.append(f'{attach[i]},{attach[i+1]}')
but then I have to remove half of rows because it also give 'b' ,'c' and so on. I thought maybe there is a better way
You can use zip() to achieve this as:
my_list = ['a','b','c','d','e','f','g','k']
new_list = list(zip(my_list[::2], my_list[1::2]))
where new_list will hold:
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'k')]
This will work to get only the pairs, i.e. if number of the elements in the list are odd, you'll loose the last element which is not as part of any pair.
If you want to preserve the last odd element from list as single element tuple in the final list, then you can use itertools.zip_longest() (in Python 3.x, or itertools.izip_longest() in Python 2.x) with list comprehension as:
from itertools import zip_longest # In Python 3.x
# from itertools import izip_longest ## In Python 2.x
my_list = ['a','b','c','d','e','f','g','h', 'k']
new_list = [(i, j) if j is not None else (i,) for i, j in zip_longest(my_list[::2], my_list[1::2])]
where new_list will hold:
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h'), ('k',)]
# last odd number as single element in the tuple ^
You have to increment iterator i.e by i by 2 when moving forward
Category=[]
for i in range(0, len(attach), 2):
Category.append(f'{attach[i]},{attach[i+1]}')
Also, you don't need the if condition, if the len(list) is always even
lis2 = [(lis[i],lis[i+1]) for i in range(0,len(lis),2)]
lis2
You can use list comprehension
Here is my list:
[(('A', 'B'), ('C', 'D')), (('E', 'F'), ('G', 'H'))]
Basically, I'd like to get:
[('A', 'C'), ('E', 'G')]
So, I'd like to select first elements from the lowest-level lists and build mid-level lists with them.
====================================================
Additional explanation below:
I could just zip them by
list(zip([w[0][0] for w in list1], [w[1][0] for w in list1]))
But later I'd like to add a condition: the second elements in the lowest level lists must be 'B' and 'D' respectively, so the final outcome should be:
[('A', 'C')] # ('E', 'G') must be sorted out
I'm a beginner, but can't find the case anywhere... Would be grateful for help.
I'd do it the following way
list = [(('A', 'B'), ('C', 'D')), (('E', 'F'), ('G', 'H'))]
out = []
for i in list:
listAux = []
for j in i:
listAux.append(j[0])
out.append((listAux[0],listAux[1]))
print(out)
I hope that's what you're looking for.
I am using python regular expressions. I want all colon separated values in a line.
e.g.
input = 'a:b c:d e:f'
expected_output = [('a','b'), ('c', 'd'), ('e', 'f')]
But when I do
>>> re.findall('(.*)\s?:\s?(.*)','a:b c:d')
I get
[('a:b c', 'd')]
I have also tried
>>> re.findall('(.*)\s?:\s?(.*)[\s$]','a:b c:d')
[('a', 'b')]
The following code works for me:
inpt = 'a:b c:d e:f'
re.findall('(\S+):(\S+)',inpt)
Output:
[('a', 'b'), ('c', 'd'), ('e', 'f')]
Use split instead of regex, also avoid giving variable name like keywords
:
inpt = 'a:b c:d e:f'
k= [tuple(i.split(':')) for i in inpt.split()]
print(k)
# [('a', 'b'), ('c', 'd'), ('e', 'f')]
The easiest way using list comprehension and split :
[tuple(ele.split(':')) for ele in input.split(' ')]
#driver values :
IN : input = 'a:b c:d e:f'
OUT : [('a', 'b'), ('c', 'd'), ('e', 'f')]
You may use
list(map(lambda x: tuple(x.split(':')), input.split()))
where
input.split() is
>>> input.split()
['a:b', 'c:d', 'e:f']
lambda x: tuple(x.split(':')) is function to convert string to tuple 'a:b' => (a, b)
map applies above function to all list elements and returns a map object (in Python 3) and this is converted to list using list
Result
>>> list(map(lambda x: tuple(x.split(':')), input.split()))
[('a', 'b'), ('c', 'd'), ('e', 'f')]
How could i find the the set of tuples of string?
For example there is a list of [('a', 'b'), ('b', 'a'), ('c','d')]
For me ('a', 'b') is same to ('b', 'a') . Is there any function in
python which can identify and remove one of them?
Just sort your tuples:
unique = set(tuple(sorted(t)) for t in inputlist)
Demo:
>>> inputlist = [('a', 'b'), ('b', 'a'), ('c','d')]
>>> set(tuple(sorted(t)) for t in inputlist)
set([('a', 'b'), ('c', 'd')])
You could extend collections.MutableSet() (collections.abc.MutableSet in Python 3) to encapsulate that behaviour:
try:
# Python 3
from collections.abc import MutableSet
except ImportError:
# Python 2
from collections import MutableSet
class SortingSet(MutableSet):
def __init__(self, values):
self._values = set()
for v in values:
self.add(v)
def __repr__(self):
return '<{}({}) at {:x}>'.format(
type(self).__name__, list(self._values), id(self))
def __contains__(self, value):
return tuple(sorted(value)) in self._values
def __iter__(self):
return iter(self._values)
def __len__(self):
return len(self._values)
def add(self, value):
self._values.add(tuple(sorted(value)))
def discard(self, value):
self._values.discard(tuple(sorted(value)))
Demo:
>>> inputlist = [('a', 'b'), ('b', 'a'), ('c','d')]
>>> sset = SortingSet(inputlist)
>>> sset
<SortingSet([('a', 'b'), ('c', 'd')]) at 106b74c50>
>>> ('d', 'c') in sset
True
How about:
list_ = [('a', 'b'), ('b', 'a'), ('c','d')]
set_ = set(frozenset(tuple) for tuple in list_)
print(set_)
? Tested on CPython 3.4.
The answers so far do not preserve order at all, if that is important to you then use this:
>>> from collections import OrderedDict
>>> items = [('a', 'b'), ('b', 'a'), ('c','d')]
>>> OrderedDict((frozenset(x), x) for x in items).values()
[('b', 'a'), ('c', 'd')]
This keeps the order and you said you could remove one of the duplicates (which it keeps the last)
Also the answers given so far also alter the elements:
>>> set(tuple(sorted(t)) for t in [('b', 'a'), ('c', 'd')])
set([('a', 'b'), ('c', 'd')])
>>> set(frozenset(tuple) for tuple in [('b', 'a'), ('c', 'd')])
set([frozenset(['a', 'b']), frozenset(['c', 'd'])])
This will keep the elements the same
>>> OrderedDict((frozenset(x), x) for x in [('b', 'a'), ('c', 'd')]).values()
[('b', 'a'), ('c', 'd')]
This question already has answers here:
Operation on every pair of element in a list
(5 answers)
Closed 8 months ago.
I have a list L = [a, b, c] and I want to generate a list of tuples :
[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...]
I tried doing L * L but it didn't work. Can someone tell me how to get this in python.
You can do it with a list comprehension:
[ (x,y) for x in L for y in L]
edit
You can also use itertools.product as others have suggested, but only if you are using 2.6 onwards. The list comprehension will work will all versions of Python from 2.0. If you do use itertools.product bear in mind that it returns a generator instead of a list, so you may need to convert it (depending on what you want to do with it).
The itertools module contains a number of helpful functions for this sort of thing. It looks like you may be looking for product:
>>> import itertools
>>> L = [1,2,3]
>>> itertools.product(L,L)
<itertools.product object at 0x83788>
>>> list(_)
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
Take a look at the itertools module, which provides a product member.
L =[1,2,3]
import itertools
res = list(itertools.product(L,L))
print(res)
Gives:
[(1,1),(1,2),(1,3),(2,1), .... and so on]
Two main alternatives:
>>> L = ['a', 'b', 'c']
>>> import itertools
>>> list(itertools.product(L, L))
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
>>> [(one, two) for one in L for two in L]
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
>>>
the former one needs Python 2.6 or better -- the latter works in just about any Python version you might be tied to.
x = [a,b,c]
y = []
for item in x:
for item2 in x:
y.append((item, item2))
Maybe not the Pythonic way but working
Ok I tried :
L2 = [(x,y) for x in L for x in L] and this got L square.
Is this the best pythonic way to do this? I would expect L * L to work in python.
The most old fashioned way to do it would be:
def perm(L):
result = []
for i in L:
for j in L:
result.append((i,j))
return result
This has a runtime of O(n^2) and is therefore quite slow, but you could consider it to be "vintage" style code.