Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I transform a multi-level list into a list of strings in Python?

Tags:

python

list

I have a list that looks something like this:

a = [('A', 'V', 'C'), ('A', 'D', 'D')]

And I want to create another list that transforms a into:

['AVC', 'ADD']

How would I go on to do this?

like image 554
Ben Forsrup Avatar asked Jan 26 '16 14:01

Ben Forsrup


People also ask

How do I convert a nested list to a string in Python?

There is no need in square brackets inside join() it could be: ' '. join(str(c) for c in lst) or ' '. join(map(str, lst)) .

How do you turn all items in a list into a string?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I convert a nested list to one list?

In this example, we will use list comprehension to Iterate the list first, and then we are iterating the sub-list using for loop. After that, we are appending the element in our new list “flatList” using a List Comprehension which gives us a flat list of 1 dimensional.

How do I make a list of strings in Python?

To create a list of strings, first use square brackets [ and ] to create a list. Then place the list items inside the brackets separated by commas. Remember that strings must be surrounded by quotes. Also remember to use = to store the list in a variable.


3 Answers

Use str.join() in a list comprehension (works in both Python 2.x and 3.x):

>>> a = [('A', 'V', 'C'), ('A', 'D', 'D')]
>>> [''.join(x) for x in a]
['AVC', 'ADD']
like image 93
Eugene Yarmash Avatar answered Oct 12 '22 02:10

Eugene Yarmash


You could map str.join to each tuple in a:

Python 2:

>>> map(''.join, a)
['AVC', 'ADD']

In Python 3, map is an iterable object so you'd need to materialise it as a list:

>>> list(map(''.join, a))
['AVC', 'ADD']
like image 25
Peter Wood Avatar answered Oct 12 '22 03:10

Peter Wood


Using reduce is another option:

>>> a = [('A','V','C'), ('A','D','D')]

In Python 2:

>>> [reduce(lambda x, y: x + y , i) for i in a]
['AVC', 'ADD']

In Python 3 (Thanks for eugene's suggestion):

>>> from functools import reduce
>>> [reduce(lambda x, y: x + y , i) for i in a]
['AVC', 'ADD']
like image 6
Quinn Avatar answered Oct 12 '22 02:10

Quinn