0
votes

I have a list = ['0.2 0.2 0.3 0.2 0.3', '0.4 0.3 0.1 0.5 0.1', '0.3 0.3 0.5 0.2 0.4', '0.1 0.2 0.1 0.1 0.2'] and I need to put a comma to separate the elements like that: '0.2, 0.2, 0.3, 0.2, 0.3'... I am parsing a file and I got stuck in this step.

I have tried this:

with open('profileKmer.txt') as f:

    lines = f.read().splitlines()
    prof = [x.strip(' ') for x in lines[4:8]]
    profile = []
    for element in prof:
        if element.startswith('0'):
            profile.extend(element.split(','))
    print(profile)

But I didn't get what I wanted.

The data looks like that:

headline
input
ACCTGTTTATTGCCTAAGTTCCGAACAAACCCAATATAGCCCGAGGGCCT
5
0.2 0.2 0.3 0.2 0.3 
0.4 0.3 0.1 0.5 0.1
0.3 0.3 0.5 0.2 0.4
0.1 0.2 0.1 0.1 0.2

I really appreciate any insight.

1
You can use the string builtin split with a ' ' argument to split on single spaces into a list. It's not really clear whether you want your output to be a python list or a string with commas separating the numbers - Andrew
try [','.join(s.split()) for s in l] where l is your list.. (please refrain from using list as var name) - iamklaus
How about foo.split() and then ",".join(foo). This is assuming that you want a comma separated set of strings, otherwise you are done after the foo.split(), potentially with a list.extend if you want them all in one list. - Bas Jansen
I want the data = ['0.2, 0.2, 0.3, 0.2, 0.3', '0.4, 0.3, 0.1, 0.5, 0.1', '0.3, 0.3, 0.5, 0.2, 0.4', '0.1, 0.2, 0.1, 0.1, 0.2'] because they will serve as values in a dictionary. - Paulo Sergio Schlogl
I do not use list as a name for list. thats was just to show the input. I really sorry but i wont be able to put the input correctely. line0 head line, line[1] number and line[4:8] a kind of array 0.2, 0.2, 0.3, 0.2, 0.3...thanks - Paulo Sergio Schlogl

1 Answers

0
votes

You can try this:

def trial(list):
  new_list = []

  for item in list:
      temp_item = ",".join(item.split())
      new_list.append(temp_item)

  print(new_list)
  # Result:
  # ['0.2,0.2,0.3,0.2,0.3', '0.4,0.3,0.1,0.5,0.1', '0.3,0.3,0.5,0.2,0.4', '0.1,0.2,0.1,0.1,0.2']
if __name__ == '__main__':
  list = ['0.2 0.2 0.3 0.2 0.3', '0.4 0.3 0.1 0.5 0.1', '0.3 0.3 0.5 0.2 0.4', '0.1 0.2 0.1 0.1 0.2']
  trial(list)