Python - convert list of tuples to string - python

Which is the most pythonic way to convert a list of tuples to string?
I have:
[(1,2), (3,4)]
and I want:
"(1,2), (3,4)"
My solution to this has been:
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
Is there a more pythonic way to do this?

You can try something like this (see also on ideone.com):
myList = [(1,2),(3,4)]
print ",".join("(%s,%s)" % tup for tup in myList)
# (1,2),(3,4)

you might want to use something such simple as:
>>> l = [(1,2), (3,4)]
>>> str(l).strip('[]')
'(1, 2), (3, 4)'
.. which is handy, but not guaranteed to work correctly

How about:
>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'

The most pythonic solution is
tuples = [(1, 2), (3, 4)]
tuple_strings = ['(%s, %s)' % tuple for tuple in tuples]
result = ', '.join(tuple_strings)

How about
l = [(1, 2), (3, 4)]
print repr(l)[1:-1]
# (1, 2), (3, 4)

I think this is pretty neat:
>>> l = [(1,2), (3,4)]
>>> "".join(str(l)).strip('[]')
'(1,2), (3,4)'
Try it, it worked like a charm for me.

Three more :)
l = [(1,2), (3,4)]
unicode(l)[1:-1]
# u'(1, 2), (3, 4)'
("%s, "*len(l) % tuple(l))[:-2]
# '(1, 2), (3, 4)'
", ".join(["%s"]*len(l)) % tuple(l)
# '(1, 2), (3, 4)'

Related

Given a List get all the combinations of tuples without duplicated results

I have a list=[1,2,3,4]
And I only want to receive tuple results for like all the positions in a matrix, so it would be
(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4)
I've seen several codes that return all the combinations but i don't know how to restrict it only to the tuples or how to add the (1,1),(2,2),(3,3),(4,4)
Thank you in advance.
You just need a double loop. A generator makes it easy to use
lst = [1,2,3,4]
def matrix(lst):
for i in range(len(lst)):
for j in range(len(lst)):
yield lst[i], lst[j]
output = [t for t in matrix(lst)]
print(output)
Output:
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]
If you just want to do this for making pairs of all symbols in the list
tuple_pairs = [(r,c) for r in lst for c in lst]
If you have instead some maximum row/colum numbers max_row and max_col you could avoid making the lst=[1,2,3,4] and instead;
tuple_pairs = [(r,c) for r in range(1,max_row+1) for c in range(1,max_col+1)]
But that's assuming that the lst's goal was to be = range(1, some_num).
Use itertools.product to get all possible combinations of an iterable object. product is roughly equivalent to nested for-loops with depth specified by the keyword parameter repeat. It returns an iterator.
from itertools import product
lst = [1, 2, 3, 4]
combos = product(lst, repeat=2)
combos = list(combos) # cast to list
print(*combos, sep=' ')
Diagonal terms can be found in a single loop (without any extra imports)
repeat = 2
diagonal = [(i,)*repeat for i in lst]
print(*diagonal sep=' ')
You can do that using list comprehension.
lst=[1,2,3,4]
out=[(i,i) for i in lst]
print(out)
Output:
[(1, 1), (2, 2), (3, 3), (4, 4)]

How to convert each pair of list into tuple in python

I want to convert list = [1,4,2,3,0] to list_tup = [(1,4),(4,2),(2,3),(3,0)]. You can see my code below but it outputs [(1,4),(2,3)]. I am wondering how to adjust indices in zip.
list=[1,4,2,3,0]
list_tup = tuple(zip(list[0::2], list[1::2]))
Try zipping the whole list with the list without the first element:
l = [1,4,2,3,0]
print(list(zip(l, l[1:])))
Or use unpack *:
l = [1,4,2,3,0]
print([*zip(l, l[1:])])
They both output:
[(1, 4), (4, 2), (2, 3), (3, 0)]
Try Zipping whole list without first element of the list
l = [1,4,2,3,0]
print(list(zip(l, l[1:])))
output:
[(1, 4), (4, 2), (2, 3), (3, 0)]

Sort out pairs with same members but different order from list of pairs

From the list
l =[(3,4),(2,3),(4,3),(3,2)]
I want to sort out all second appearances of pairs with the same members in reverse order. I.e., the result should be
[(3,4),(2,3)]
What's the most concise way to do that in Python?
Alternatively, one might do it in a more verbose way:
l = [(3,4),(2,3),(4,3),(3,2)]
L = []
omega = set([])
for a,b in l:
key = (min(a,b), max(a,b))
if key in omega:
continue
omega.add(key)
L.append((a,b))
print(L)
If we want to keep only the first tuple of each pair:
l =[(3,4),(2,3),(4,3),(3,2), (3, 3), (5, 6)]
def first_tuples(l):
# We could use a list to keep track of the already seen
# tuples, but checking if they are in a set is faster
already_seen = set()
out = []
for tup in l:
if set(tup) not in already_seen:
out.append(tup)
# As sets can only contain hashables, we use a
# frozenset here
already_seen.add(frozenset(tup))
return out
print(first_tuples(l))
# [(3, 4), (2, 3), (3, 3), (5, 6)]
This ought to do the trick:
[x for i, x in enumerate(l) if any(y[::-1] == x for y in l[i:])]
Out[23]: [(3, 4), (2, 3)]
Expanding the initial list a little bit with different orderings:
l =[(3,4),(2,3),(4,3),(3,2), (1,3), (3,1)]
[x for i, x in enumerate(l) if any(y[::-1] == x for y in l[i:])]
Out[25]: [(3, 4), (2, 3), (1, 3)]
And, depending on whether each tuple is guaranteed to have an accompanying "sister" reversed tuple, the logic may change in order to keep "singleton" tuples:
l = [(3, 4), (2, 3), (4, 3), (3, 2), (1, 3), (3, 1), (10, 11), (10, 12)]
[x for i, x in enumerate(l) if any(y[::-1] == x for y in l[i:]) or not any(y[::-1] == x for y in l)]
Out[35]: [(3, 4), (2, 3), (1, 3), (10, 11), (10, 12)]
IMHO, this should be both shorter and clearer than anything posted so far:
my_tuple_list = [(3,4),(2,3),(4,3),(3,2)]
set((left, right) if left < right else (right, left) for left, right in my_tuple_list)
>>> {(2, 3), (3, 4)}
It simply makes a set of all tuples, whose members are exchanged beforehand if first member is > second member.

sorting nested tuple list

So, what I am trying to do, is to sort a list with that contains (num, tuple) I want to sort it first by the second value of the tuple and if 2 are equal, I want to sort it by the num(of the first tuple).
So lets say I have:
l = [(1,(2,3)),(3,(2,1)),(2,(2,1))]
print(l.sort(key=something))
[(2,(2,1)), (3,(2,1)), (1,(2,3))]
I have tried:
l.sort(key=itemgetter(1,0)
Of course it didn't work. Any ideas?
Thank you.
operator.itemgetter works fine:
>>> from operator import itemgetter
>>> l = [(1,(2,3)),(3,(2,1)),(2,(2,1))]
>>> l.sort(key=itemgetter(1,0))
>>> print(l)
[(2, (2, 1)), (3, (2, 1)), (1, (2, 3))]
>>>
I think the problem is that you tried to print the result of list.sort. You cannot do this because it is an in-place method (it always returns None).
>>> l = [(1,(2,3)),(3,(2,1)),(2,(2,1))]
>>> sorted(l, key=lambda t: (t[1][1],t[0]))
[(2, (2, 1)), (3, (2, 1)), (1, (2, 3))]
Or:
>>> from operator import itemgetter
>>> sorted(l, key=itemgetter(1,0))
[(2, (2, 1)), (3, (2, 1)), (1, (2, 3))]
this works too:
l.sort(key=lambda x: x[::-1])
Note that list.sort sorts the list in place, so print(l.sort(key=something)) would print None.

Delete (a,b) from a python list of tuples if (b,a) exists

From a python list of tuples (which is essentially a cartesian product of a list with itself) I want to delete (a,b) if (b,a) is in the list.Only one of (a,b) or (b,a) must be retained. So a list
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
must reduce to
[(1,2),(1,3),(2,3)]
(Although deleting (1,2) and retaining (2,1) is fine)
I tried doing this but I am not sure about deleting from a list while iterating over it. This doesn't work. (Gives me [(1, 2), (2, 1), (2, 3), (3, 1), (3, 3)])
[pairs.remove((a,b)) for (a,b) in pairs if ((b,a) in pairs)]
Why delete the incorrect ones from the list?
Use itertools.combinations to generate the correct ones instead.
>>> import itertools
>>> list(itertools.combinations((1, 2, 3), 2))
[(1, 2), (1, 3), (2, 3)]
>>> [el for el in pairs if el[0] < el[1]]
[(1,2),(1,3),(2,3)]
pairs = [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
new_pairs = []
for a, b in pairs:
if (a, b) in new_pairs or (b, a) in new_pairs:
pass
else:
new_pairs += [(a,b)]
new_pairs = [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]

Categories

Resources