Coding Problem
💬 Coding Problem: Given a nested Python listing, i.e., a listing of lists. Easy methods to convert it to a string listing, so that every interior listing turns into a single string?
Think about the next examples:
1. Enter:[['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']]
Output:['hello', 'world']
2. Enter:[['h', 'i'], ['!']]
Output:['hi', '!']
3. Enter:[['h', 'i'], []]
Output:['hi', '']
Technique 1: Becoming a member of Interior Lists Utilizing Record Comprehension
The Python one-liner expression [''.join(inner) for inner in lst]
combines a easy listing comprehension assertion with the string.be a part of()
methodology to mix an interior listing right into a single string and repeat this for every interior listing.
Right here’s a code instance:
def f(lst): '''Converts enter listing of lists of strings to listing of strings.''' return [''.join(inner) for inner in lst] # Instance 1: lst = [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']] print(f(lst)) # ['hello', 'world'] # Instance 2: lst = [['h', 'i'], ['!']] print(f(lst)) # ['hi', '!'] # Instance 3: lst = [['h', 'i'], []] print(f(lst)) # ['hi', '']
You could need to watch the next background video on listing comprehension that can reply all of your questions on this thrilling Python function:
👉 Really helpful Tutorial: Python Record Comprehension
Technique 2: Nested For Loop and String Concatenation
A really clunky option to convert a nested listing of strings to a string listing is to assemble every string at a time utilizing two nested for
loops.
- The outer loop iterates over all lists within the nested listing.
- The interior loop iterates over all strings and aggregates these strings in a single bigger string utilizing the string concatenation operator
+=
.
You gather every of these constructed strings in a variable that factors to an initially empty listing utilizing the listing.append()
methodology.
Right here’s a code instance:
def f(lst): '''Converts enter listing of lists of strings to listing of strings.''' tmp = [] for interior in lst: s="" for x in interior: s += x tmp.append(s) return tmp # Instance 1: lst = [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']] print(f(lst)) # ['hello', 'world'] # Instance 2: lst = [['h', 'i'], ['!']] print(f(lst)) # ['hi', '!'] # Instance 3: lst = [['h', 'i'], []] print(f(lst)) # ['hi', '']
👉 Really helpful Tutorial: It is best to undoubtedly take a look at our tutorial on string concatenation which signifies that it’s not tremendous environment friendly as a result of strings are immutable and you might want to create a brand new string in every iteration.
Technique 3: Mapping Every Interior Record to a Concatenated String
One other nice option to concatenate the strings of every interior listing to a single string is listing(map(''.be a part of, lst))
. You cross the ''.be a part of
methodology on the empty string ''
into the map()
operate that then applies this methodology to every aspect in an iterable lst
that you simply cross as a second argument.
Right here’s a code instance:
def f(lst): '''Converts enter listing of lists of strings to listing of strings.''' return listing(map(''.be a part of, lst)) # Instance 1: lst = [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']] print(f(lst)) # ['hello', 'world'] # Instance 2: lst = [['h', 'i'], ['!']] print(f(lst)) # ['hi', '!'] # Instance 3: lst = [['h', 'i'], []] print(f(lst)) # ['hi', '']
Be aware that we have to wrap the output of the map()
operate right into a listing()
constructor to create a listing from the iterable object. The return worth of the map()
operate is the iterable map
object that doesn’t look very fairly to us people.
In any case, you need to undoubtedly take a look at this video on the map()
operate that can educate you all you might want to know!
👉 Really helpful Tutorial: Python map()
— Lastly Mastering the Python Map Operate
Abstract
You have got realized that the next strategies remedy your downside X
- Technique 1:
[''.join(inner) for inner in lst]
- Technique 2: nested
for
loops - Technique 3:
listing(map(''.be a part of, lst))
💡 Conclusion: Record comprehension (Technique 1) is the very best and most Pythonic option to convert a nested listing to a string listing as a result of it’s the best to make use of, extra concise than the nested for loop (Technique 2), and doesn’t require difficult nested operate calls (Technique 3).
That’s my opinion anyway… 🙂
Whereas working as a researcher in distributed techniques, Dr. Christian Mayer discovered his love for instructing laptop science college students.
To assist college students attain larger ranges of Python success, he based the programming training web site Finxter.com. He’s writer of the favored programming e book Python One-Liners (NoStarch 2020), coauthor of the Espresso Break Python sequence of self-published books, laptop science fanatic, freelancer, and proprietor of one of many high 10 largest Python blogs worldwide.
His passions are writing, studying, and coding. However his best ardour is to serve aspiring coders by way of Finxter and assist them to spice up their abilities. You’ll be able to be a part of his free e mail academy right here.