input: Write a function to optimize a given piece of inefficient Python code that filters elements from a list based on a condition. The function should return the optimized version of the code. If the input code is already optimized, it should return the original code.
  
  assert optimize_code("data = [1, 2, 3, 4]\nresult = []\nfor x in data:\n if x > 2:\n  result.append(x)") == "data = [1, 2, 3, 4]\nresult = [x for x in data if x > 2]"
  
  assert optimize_code("data = [1, 3, 5]\nfiltered = [i for i in data if i % 2 != 0]") == "data = [1, 3, 5]\nfiltered = [i for i in data if i % 2 != 0]"
output: def optimize_code(code):
      if "for" in code and "if" in code and "append" in code:
          lines = code.split("\n")
          for i, line in enumerate(lines):
              if "for" in line and "in" in line:
                  for_line = line
                  if_line = lines[i + 1]
                  append_line = lines[i + 2]
                  if "if" in if_line and "append" in append_line:
                      var = for_line.split()[1]
                      condition = if_line.split("if ")[1].strip()
                      result_var = append_line.split(".")[0].strip()
                      optimized_code = f"{result_var} = [{var} for {var} in {for_line.split('in')[1].strip()} if {condition}]"
                      return "\n".join(lines[:i] + [optimized_code])
      return code