2

I have the following lis of tuples after making a lot of reformating:

[[(('A', 'X'), ('43,23', 'Y'), ('wepowe', 'd'))]]

How can I reformat into:

'A', '43,23', 'wepowe'

I tried to:

[' '.join(map(str,lis[0][0])) for x in lis]

and

[' '.join(map(str,lis[0][:1])) for x in lis]

and

' '.join(map(str, lis))

However, I do not get the desired format. Which is the easist way of reformating tuples and lists like the above?.

tumbleweed
  • 4,624
  • 12
  • 50
  • 81

3 Answers3

6

You can use a list comprehension like this:

my_list = [(('A', 'X'), ('43,23', 'Y'), ('wepowe', 'd'))]
result = [item[0] for item in my_list[0]]

Output:

>>> result
['A', '43,23', 'wepowe']
ettanany
  • 19,038
  • 9
  • 47
  • 63
  • My problem was actually entering to the first parethesis, is that done with `item[0]`? – tumbleweed Jan 05 '17 at 17:34
  • 1
    It is done by `my_list[0]`, inside your list you have one element, to access it you need to use `my_list[0]`, then for each item, to access the first sub-item you should use `item[0]` – ettanany Jan 05 '17 at 17:34
3

You may use zip as:

>>> my_list = [(('A', 'X'), ('43,23', 'Y'), ('wepowe', 'd'))]
>>> new_list , _ = zip(*my_list[0])
#              ^ replace this with some variable in case you also want the
#                elements at `1`st index of each tuple

Value hold by new_list will be:

>>> new_list
('A', '43,23', 'wepowe')
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • Thanks!, I liked this solution, could you explain a little bit what is happening and if this is the most efficient?. – tumbleweed Jan 05 '17 at 17:40
  • 1
    Check [zip document](https://docs.python.org/2/library/functions.html#zip). You will get the idea on what it does. Also, you may find [this post](http://stackoverflow.com/questions/13180861/zip-as-a-list-comprehension) helpful. In my solution `zip(*my_list[0])`, `*` is used to unpack the list and then zip is performed on the unpacked list – Moinuddin Quadri Jan 05 '17 at 17:43
  • Actually it worked 1 minute ago... I am getting this: `IndexError: list index out of range` – tumbleweed Jan 05 '17 at 17:47
  • 1
    You must have changed the structure of your input list OR, you would not be calling the `zip` function as I did :) – Moinuddin Quadri Jan 05 '17 at 17:48
2

Before you write any list comprehensions lets iterate the list using 2 for loops, like:

tups = [(('A', 'X'), ('43,23', 'Y'), ('wepowe', 'd'))]

for item in tups:
    for j in item:
        print j[0]

Now if you were to see we get the first element of each tuple we are looking for, we can convert it to a list comprehension expression like so:

' '.join(str(j[0]) for item in tups for j in item)