Gerry Julian - 1 year ago 53

Python Question

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?

Answer Source

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.