Skip to content Skip to sidebar Skip to footer

How To Join Many "listed" Tuples Into One Tuple In Python?

There are few answers for the problem on in Python, How to join a list of tuples into one list?, How to merge two tuples in Python?, How To Merge an Arbitrary Number of Tuples in P

Solution 1:

tuple(ast.literal_eval(x) for x in my_open_file if x.strip())

I suppose ...

Solution 2:

a = (1, 5)

b = (5, 3)

c = (10, 3)

d = (5, 4)

e = (1, 3)

f = (2, 5)

g = (1, 5)

tul = (a, b, c, d, e, f, g)

print(tul)

Solution 3:

list comprehension as mentioned in your linked answers works with tuple() as well:

print tuple((1,2) for x in xrange(0, 10))

Leaving off the "tuple" or "list" at the beginning will return a generator.

print ((1,2) for x in xrange(0, 10))

Using [] instead of () is short-hand for list:

print [(1,2) for x in xrange(0, 10)]

The evaluation of the for statement is returning a generator, while the keywords or bracket are telling python to unpack it into that type.

Solution 4:

Here is my problem: I want to know how many times a tuple appears in my 'result'. So I did this:

from collections import Counter
liste = [1,2,3,5,10]
liste2 = [[1,2,3,5,10], [1,2], [1,5,10], [3,5,10], [1,2,5,10]]
for elt in liste2:
    syn = elt # identify each sublist of liste2 as syn
    nTuple = len(syn)   # number of elements in the synfor i in liste:
        myTuple = ()
        if synset.count(i): # check if an item of liste is in liste2
        myTuple = (i, nTuple)
        iflen(myTuple) == '0': # remove the empty tuplesdel(myTuple)
        else:
            result = [myTuple] 
            c = Counter(result)
            for item in c.items():
                print(item)

and I got these results:

((1, 5), 1)

((2, 5), 1)

((3, 5), 1)

((5, 5), 1)

((10, 5), 1)

((1, 2), 1)

((2, 2), 1)

((1, 3), 1)

((5, 3), 1)

((10, 3), 1)

((3, 3), 1)

((5, 3), 1)

((10, 3), 1)

((1, 4), 1)

((2, 4), 1)

((5, 4), 1)

((10, 4), 1)

Instead of having some elts N times (e.g ((5, 3), 1) and ((10, 3), 1) appear twice), I would like to have a tuple(key,value) where value = the number of times key appears in 'result'. That why I thought I can join my listed tuples in one tuple before using Counter.

I would like to get 'result' like this:

((1, 5), 1)

((2, 5), 1)

((3, 5), 1)

((5, 5), 1)

((10, 5), 1)

((1, 2), 1)

((2, 2), 1)

((1, 3), 1)

((5, 3), 2)

((10, 3), 2)

((3, 3), 1)

((1, 4), 1)

((2, 4), 1)

((5, 4), 1)

((10, 4), 1)

Thanks

Post a Comment for "How To Join Many "listed" Tuples Into One Tuple In Python?"