-1

How do I add a dot into a Python list?

For example

 groups = [0.122, 0.1212, 0.2112]

If I want to output this data, how would I make it so it is like

122, 1212, 2112

I tried write(groups...[0]) and further research but didn't get far. Thanks.

Thankyou

user3511074
  • 1
  • 1
  • 1
  • 2
    You mean you want to find the decimal portion of the floating point numbers in your list? – Martijn Pieters Apr 08 '14 at 13:05
  • 1
    @user3511074 Then you should edit your question to make it more accurate and descriptive... And while you're on it, take a look to this: http://stackoverflow.com/questions/3886402/python-how-to-get-numbers-after-decimal-point – Savir Apr 08 '14 at 13:08

3 Answers3

2
[str(g).split(".")[1] for g in groups]

results in

['122', '1212', '2112']

Edit:

Use it like this:

groups = [0.122, 0.1212, 0.2112]
decimals = [str(g).split(".")[1] for g in groups]
0

This should do it:

groups = [0.122, 0.1212, 0.2112]
import re
groups_str = ", ".join([str(x) for x in groups])
re.sub('[0-9]*[.]', "", groups_str)
  • [str(x) for x in groups] will make strings of the items.
  • ", ".join will connect the items, as a string.

import re allows you to replace regular expressions:

  • using re.sub, the regular expression is used by replacing any numbers followed by a dot by nothing.

EDIT (no extra modules):

Working with Lutz' answer, this will also work in the case there is an integer (no dot):

decimals = [str(g).split("0.") for g in groups]
decimals = decimals = [i for x in decimals for i in x if i != '']

It won't work though when you have numbers like 11.11, where there is a part you don't want to ignore in front of the dot.

Community
  • 1
  • 1
PascalVKooten
  • 20,643
  • 17
  • 103
  • 160
0

You could use a list comprehension and return a list of strings

groups = [0.122, 0.1212, 0.2112]
[str(x).split(".")[1] for x in groups]

Result

['122', '1212', '2112']

The list comprehension is doing the following:

  • Turn each list element into a string
  • Split the string about the "." character
  • Return the substring to the right of the split
  • Return a list based on the above logic
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218