Reputation: 43
I'm facing a trouble with creating a new tuple. I'm kinda new in python.
Suppose I have a list of tuple :
a = [1,2,6,4,5]
b = [3,7,3,4,6]
[((11, 5, 6), n), ((9, 6, 3), n), ((9, 2, 7), n), ((8, 4, 4), n), ((4, 1, 3), n)]
which belongs to [(a+b,a,b),n=count(zip(a,b)),...........]
My final goal is to make a tuple like this: (removing a+b, and put 'n' value into the tuple)
[(5,6,n), (6,3,n), .... ]
[(a,b,n), .....]
is there a way to make this happen?
Upvotes: 0
Views: 97
Reputation: 4629
I don't understand very well your question, but suppose we know the 'n' value for every tuple (i fixed my n's to 1)
The naive solution is (without tuple unpacking)
n = 1
x = [((11, 5, 6), n), ((9, 6, 3), n), ((9, 2, 7), n), ((8, 4, 4), n), ((4, 1, 3), n)]
y= [(tuple_[0][1],tuple_[0][2], tuple_[1]) for tuple_ in x]
print(y)
which prints
[(5, 6, 1), (6, 3, 1), (2, 7, 1), (4, 4, 1), (1, 3, 1)]
Upvotes: 0
Reputation: 74675
Simply use tuple unpacking:
[(a, b, n) for ((_, a, b), n) in T]
Where T
is the input and the result is in the requested form.
Example:
>>> T = [((11, 5, 6), 1), ((9, 6, 3), 2), ((9, 2, 7), 3), ((8, 4, 4), 4), ((4, 1, 3), 5)]
>>> [(a, b, n) for ((_, a, b), n) in T]
[(5, 6, 1), (6, 3, 2), (2, 7, 3), (4, 4, 4), (1, 3, 5)]
I've replaced the n
's with numbers 1 to 5.
Upvotes: 1
Reputation: 1741
It is a bit confusing what you wrote.
Maybe you want this:
zip(a,b,[sum(x) for x in zip(a,b)])
What it does:
zip()
returs a list of tuplesNote that tuples and list are two different data structures.
In your question, a = []
and b = [] are lists of integers, not tuples.
a syntax of [ f(x) for x in g(y,z)]
is equivalent to pseudo-code:
for each_item in iterable_like_a_list_is:
apply f() to each_item
return a list of f(x) items
It is a list comprehension.
zip(x, y, z)
to three lists.
In your case, a, b and the a+b obtained at step 2.Upvotes: 0