Home > Enterprise >  How can I make a list from list of rows?
How can I make a list from list of rows?

Time:02-26

I have this list:

d=['-5 -50', '-2 -15 .5', '50;-2e2', '-1 -12', '0,-40']

How i can remove symbol such as , . ;(and also third number if it existі) from this list and make list like that

d1=[-5 -50], [-2 -15], [50 -2e2], [-1 -12], [0,-40]

i tried:

f1 = open('tester2.txt', 'r')
lst = []
c = f1.readlines()
for i in c:
   lst.append(i.strip())
print(lst)

line = '*'.join(lst)
line1 = line.replace(',', ' ')
line2 = line1.replace('.', ' ')
line3 = line2.replace(';', ' ')
print(line3)

l=line3.split('*')
lst1=[]
for k in l:
   lst1.append(k)
print(lst1) 


lst2 = []
for u in lst1:
  v = u.split(' ')
  lst2.append(v)
print(lst2) 
del lst2[1][2]
del lst2[1][2]

for k in lst2:
   for s in range(len(k)):
      k[s] = int(k[s])
print(lst2) 

CodePudding user response:

Use re.split() to use multiple delimiters as the field delimiters in your lines.

Use a list slice to discard the third field if it exists.

Use a list comprehension to convert all the fields to numbers.

import re

with open("tester2.txt") as f:
    lines = [line.strip() for line in f.readlines()]

for i, line in enumerate(lines):
    lines[i] = [int(num) for num in re.split(r'[\s.,;]', line)[:2]]

print(lines)
  • Related