Python function list insertion
I am trying to write line 4-5 code in one line using list-comprehentions. But the problem here is that I cannot use the insert function, so I am wondering if there is a workaround for this?
Source:
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've 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 ran into the following error:
NameError: global name 'insert' is undefined
I tried to use insert because the challenge is to reorder the elements in the list using the number that appears in each word.
for example i have is2 Th1is T4est 3a
as input and it should look like this:Th1is is2 3a T4est
source to share
Instead of using lists, you should just be a sort
list, using these numbers in a key function eg. extracting numbers using 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']
source to share
You can implement your original idea by splitting the code into a few simple functions and making a list of the correct size (filled with None
s) to preserve the final word order:
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 it 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))
source to share