Say I have a simple list such as "apples, bananasx2, orangesx3, pears."
Is there a function that will convert this into "apples, bananas, bananas, oranges, oranges, oranges, pears"?
I've tried to write an if loop but I can't figure out how to identify the number and also repeat the string by that number. This info is currently in dataframe columns but it doesn't have to be.
CodePudding user response:
Not sure if thats the fastest, but you could use:
import re
l = []
for elem in ["apples", "bananasx2", "orangesx3", "pears"]:
if re.search(".*x\d", elem):
word, occurrence = elem.rsplit("x", 1)
l = [word] * int(occurrence)
else:
l.append(elem)
CodePudding user response:
I would prefer more elegant code. But it works.
lis = ["apples", "bananasx2", "orangesx3", "pears"]
for index, i in enumerate(lis) :
if i[-2:-1] == "x" and i[-1].isnumeric:
lis[index] = i[:-2]
for num in range(int(i[-1])-1):
lis.append(i[:-2])