1

I have the following code snippet: I want to find the row, with the value is digit (they are integers all the time) on the column/key "Something" and delete the matched row. I have tried it with re.compile()

for row in list:
    if re.compile("\d") in row["Something"]:
        print(row)
        del (row)

How is the right implementation in this case?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
madik_atma
  • 787
  • 10
  • 28

2 Answers2

1

don't try remove items from lists while iterating, it doesn't work that well: Remove items from a list while iterating. Anyway, del row has no effect since you're just deleting the name, not the item of the list.

I'm assuming that you want to remove rows if row["Something"] is an integer value.

I would rebuild the list using a list comprehension filtering out when the data is digits only (regex can be avoided here by using isdigit()):

[row for row in lst if not row["Something"].isdigit()]

That doesn't take care of negative numbers, mind. For that you would need a regex-type check like re.match("-?\d+",row["Something"])

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

Rather than deleting your row, you might want to match those which do not contain digits:

import re
rx = re.compile(r'^\D+$')

new_rows = (row for row in lst if rx.match(row))

This yields a generator which you could either iterate over or convert it to a list entirely.
Additionally, using list as a variable name is a no-no.

Jan
  • 42,290
  • 8
  • 54
  • 79