1

I have a list:

rows=['1\t0.00032822\n', '2\t0.00029311\n', '3\t0.0002048\n',...] 

and i want to have a list with the numbers only:

['0.00032822', '0.00029311', '0.0002048',...]. 

Something like:

list = [sliceAppropiate(x) for x in rows]

2 Answers 2

4

Use a list comprehension:

>>> rows = ['1\t0.00032822\n', '2\t0.00029311\n', '3\t0.0002048\n'] 
>>> [r.split()[1] for r in rows]
['0.00032822', '0.00029311', '0.0002048']

What this does is:

  • Go through each item in rows in turn,
  • Give it the name r,
  • Split each r into a list with split(), by cutting at whitespace (which can be spaces, tabs or newlines),
  • Take item 1 from that list (where item 0 is the first one, because Python uses zero-based indexing).
Sign up to request clarification or add additional context in comments.

5 Comments

So, split by default "splits" in numbers! Nice!
@JohnZobolas Actually it splits on whitespace - from the docs I linked to: "If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace."
@JohnZobolas split splits on whitespace, which \t and \n are.
Thanks Zero and Aaron! I also used something like this to have the sum of the list of numbers: sum([(float) (r.split()[1]) for r in rows])
@JohnZobolas great! You can make that a little more efficient and readable by dropping the parentheses around float, and the square brackets around the listcomp (turning into a generator expression): sum(float(r.split()[1]) for r in rows)
0

Here is a very simple code that do it for you:

list = []
for i in range(len(rows)): # from 0 to len(rows) - 1
    list[i] = rows[i].split('\t')[1]

If need float numbers use float function:

float(rows[i].split('\t')[1])

1 Comment

Thanks! I believe that the answer with the list comprehension is better-more compact and easy to understand!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.