"""封闭自选池逐行回填,重复行复用取数但不丢失原行。""" import json watchlist = [(1, "AAA.US"), (2, "AAA.US"), (3, "BBB.HK"), (4, "XYZ"), (5, "BAD.US"), (6, "CCC.CN")] resolved = {"AAA.US": "AAA.US", "BBB.HK": "BBB.HK", "CCC.CN": "CCC.CN"} source = {"AAA.US": 18, "BBB.HK": 22, "CCC.CN": None, "OUTSIDE.US": 10} cache, output, calls = {}, [], [] for row_id, requested in watchlist: if requested not in resolved: state, value = ("ambiguous", None) if requested == "XYZ" else ("not_found", None) else: symbol = resolved[requested] if symbol not in cache: calls.append(symbol) cache[symbol] = source.get(symbol) value = cache[symbol] state = "unknown" if value is None else "pass" if 0 < value < 20 else "fail" output.append({"row_id": row_id, "requested": requested, "pe": value, "state": state}) research = sorted({row["requested"] for row in output if row["state"] == "pass"}) assert [r["row_id"] for r in output] == list(range(1, 7)) assert [r["state"] for r in output] == ["pass", "pass", "fail", "ambiguous", "not_found", "unknown"] assert calls == ["AAA.US", "BBB.HK", "CCC.CN"] and research == ["AAA.US"] assert all(r["requested"] != "OUTSIDE.US" for r in output) assert len(output) == len(watchlist) print(json.dumps({"rows": output, "fetch_symbols": calls, "research_list": research}, sort_keys=True))