tumbleweed
tumbleweed

Reputation: 4640

Problems while reformating a nested list of tuples?

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?.

Upvotes: 2

Views: 50

Answers (3)

user378704
user378704

Reputation:

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)

Upvotes: 2

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48092

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')

Upvotes: 3

ettanany
ettanany

Reputation: 19816

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']

Upvotes: 6

Related Questions