user308827
user308827

Reputation: 21961

Converting numeric list in python to text based list

How can I convert a python list like:

[0, 1/4, 2/4, 3/4 , 4/4]

into the following:

[r'$25^{th}$', r'$50^{th}$', r'$75^{th}$', r'$100^{th}$']

Here each element of the 2nd list corresponds to a percentile value E.g. in the first list the element 0 corresponds to values below the 25th percentile. I want the solution to be easily extendible to different lengths e.g. current list has 5 elements, but we could have 2 elements or 10. Is there a pythonic way to do this?

Upvotes: 0

Views: 52

Answers (2)

Harshith Thota
Harshith Thota

Reputation: 864

Lists have a function called list.extend(seq) which can dynamically extend your list with a sequence. For example:

l = [1,2,3,4]
l.extend([5,6])
print(l) # [1,2,3,4,5,6]

Now, to answer your actual question:

perclist = ["%4.2f th" % (float(i)*100) for i in fraclist]

Upvotes: 1

Anton vBR
Anton vBR

Reputation: 18906

Something like this I guess:

a = [0, 1/4, 2/4, 3/4 , 4/4]
b = [r'$%i^{th}$' % (i*100) for i in a[1:]] #skips first value

Upvotes: 0

Related Questions