Kondecigs Kondecigs - 6 months ago 10
Python Question

How to remove floats of a list of lists?

For example:

[['D', 'D', '-', '1', '.', '0'],['+', '2', '.', '0', 'D', 'D'],['D', 'D', 'D']]


This is:

D D -1.0
+2.0 D D
D D D


I want to extract the values, put in differents variables and know the line and column where the signal was (so i can put symbol that corresponds to the old value).

D D x
y D D
D D D

[['D', 'D', '-1.0'],['+2.0', 'D', 'D'],['D', 'D', 'D']]

Answer

Use re.findall. The pattern [-+]?\d*\.\d+|\d+ is used to extract float values from a string.

import re

list2d = [['D', 'D', '-', '1', '.', '0'],['+', '2', '.', '0', 'D', 'D'],['D', 'D', 'D']]
lists = list()

for l in list2d:
    s = ''.join(l)
    matches = re.findall(r"D|[-+]?\d*\.\d+|\d+", s)

    lists.append(matches)

print(lists)
# Output
[['D', 'D', '-1.0'], ['+2.0', 'D', 'D'], ['D', 'D', 'D']]
Comments