Reputation: 1165
I am trying to write a 4-5 line code in a single line by using list-comprehentions. But the problem here is that I am not able to use the insert funciton so im wondering if there is a work-around for this?
Original code:
def order(text):
text = text.split()
for x in text:
for y in x:
if y in ('1','2','3','4','5','6','7','8','9'):
final.insert(int(y)-1, x)
return final
What i have tried so far:
return [insert(int(y)-1, x) for x in text.split() for y in x if y in ('1','2','3','4','5','6','7','8','9')]
But i have faced the following error:
NameError: global name 'insert' is not defined
I have tried to use insert because the task is to re-arrange items in the list by using the number that appears in each word.
for example i have is2 Th1is T4est 3a
as input and it should come out as:
Th1is is2 3a T4est
Upvotes: 3
Views: 151
Reputation: 298196
You can implement your original idea by splitting your code up into a few simple functions and make a list of the proper size (filled with None
s) to hold the final ordering of the words:
def extract_number(text):
return int(''.join(c for c in text if c.isdigit()))
def order(text):
words = text.split()
result = [None] * len(words)
for word in words:
result[extract_number(word) - 1] = word
return ' '.join(result)
You can also do this in one line using sorted()
:
def extract_number(text):
return int(''.join(c for c in text if c.isdigit()))
def order(text):
return ' '.join(sorted(text.split(), key=extract_number))
Upvotes: 1
Reputation: 82899
Instead of using list comprehensions, you should just sort
the list using those numbers in the key function, e.g. extracting the numbers using a regular expression.
>>> import re
>>> s = "is2 Th1is T4est 3a"
>>> p = re.compile("\d+")
>>> sorted(s.split(), key=lambda x: int(p.search(x).group()))
['Th1is', 'is2', '3a', 'T4est']
Upvotes: 4