Reputation: 29
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 Python?. All the answers refer to list of tuples, so the solutions provided there seem to be useless for me.
Here is my problem, I have a file with tuples listed like this:
(1, 5)
(5, 3)
(10, 3)
(5, 4)
(1, 3)
(2, 5)
(1, 5)
I would like to join them in ONE tuple like this:
((1, 5), (5, 3), (10, 3), (5, 4), (1, 3), (2, 5), (1, 5))
Can anyone help me to solve this problem?
Thanks
Upvotes: 1
Views: 826
Reputation: 29
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 syn
for i in liste:
myTuple = ()
if synset.count(i): # check if an item of liste is in liste2
myTuple = (i, nTuple)
if len(myTuple) == '0': # remove the empty tuples
del(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
Upvotes: 0
Reputation: 620
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.
Upvotes: 0
Reputation: 7553
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)
Upvotes: 1
Reputation: 113940
tuple(ast.literal_eval(x) for x in my_open_file if x.strip())
I suppose ...
Upvotes: 1