状态:已完成
【Python 代码】将非标准数据类型转换为统一的标准类型
Thinking Process:
1. **Analyze the Request:**
* Role: Professional Programming Assistant.
* Goal: Convert non-standard data types to a unified standard type.
* Rules:
1. If achievable directly with Python code (run code -> achieve goal), return *only* the complete Python code, no explanations.
2. If not directly achievable, split into 2-5 independent sub-goals (each expressible as a complete target, context-independent). Format: "子目标:XXXXXX", one per line.
3. No extra text.
2. **Evaluate the Goal:** "将非标准数据类型转换为统一的标准类型" (Convert non-standard data types to a unified standard type).
* Is this specific enough to be a single Python script?
* "Non-standard data types" is vague. What types? JSON strings? Mixed lists? Custom objects?
* "Unified standard type" is vague. What type? String? Dict? List? JSON?
* Since the goal is abstract and depends on external context (input data, desired output type), it's not a single executable snippet that works universally without knowing the input structure and desired output structure.
* However, the prompt asks me to judge *if* it can be implemented directly.
* If I write a generic function `def normalize(x): ...`, it's code, but it might not "achieve the goal" until called with specific inputs.
* But usually, in this context, if the task is generic enough to be a utility function, it counts as "directly achievable with Python code".
* Let's look closer at the rule: "If this goal can be directly achieved with Python code, i.e., after running the code the goal is achieved".
* Running a generic function doesn't achieve the goal unless it processes specific input.
* Given the ambiguity ("non-standard", "standard"), it's hard to write a single script that *definitely* achieves the goal without more context (e.g., "Convert all inputs to strings" or "Convert JSON to Dict").
* However, often in these prompts, if it's a general transformation logic, writing a function is considered the code.
* But wait, Rule 2 says: "If not directly achievable, split into 2-5 sub-goals".
* Is "Convert non-standard data types to a unified standard type" specific enough?
* Imagine a user wants to convert various inputs (strings, numbers, objects) into a specific format (e.g., JSON string).
* If I write `import json; data = ...; print(json.dumps(data))`, that converts to a standard JSON string.
* But the prompt doesn't specify *what* standard type.
* Because the target type is undefined ("unified standard type"), the code needs to define it or accept it.
* Since the prompt asks me to judge based on the provided text, and the provided text is the *goal itself* ("将非标准数据类型转换为统一的标准类型"), it's slightly ambiguous.
* Let's consider the "Sub-goals" option. If I treat the ambiguity as a reason to split it, I might get 2-5 steps like:
1. Identify the input types.
2. Define the target standard type.
3. Implement conversion logic.
4. Handle edge cases.
5. Validate output.
* However, usually, a generic "Type Converter" class or function is considered a direct implementation.
* Let's lean towards **Rule 2 (Sub-goals)** because the goal is abstract. A single snippet of code `x = str(y)` depends on context. To *guarantee* the goal is met, we need to define what "non-standard" and "standard" mean.
* Actually, looking at the strictness: "If this goal can be directly achieved with Python code... return complete Python code".
* If I write a function `convert(data)`, running it doesn't change anything until passed data.
* But if the goal is "Write a converter", then code is enough.
* If the goal is "The data *is* converted", then code alone isn't enough (needs data).
* Given the phrasing "将...转换为..." (Convert ... to ...), it implies an action on data.
* Let's try to make it Rule 2 (Sub-goals) because "Standard Type" is not defined. A generic script needs parameters.
* Wait, if I assume the standard type is "String" or "Dict", I could write code. But without specification, splitting is safer to ensure the goal is defined and met.
* Let's look at the constraint: "Sub-goals need to be independent complete targets".
* If I split:
1. Define the unified standard type.
2. Identify the non-standard types to be converted.
3. Implement the conversion logic for each type.
4. Test the conversion with sample data.
* These are logical steps.
* However, often in these tasks, if a generic solution exists, Code is preferred.
* Let's reconsider Rule 1. "Run code -> achieve goal". If I run `print(type(json.dumps({"a": 1})))`, does it achieve "Convert non-standard to standard"?
* Since the goal is vague, Rule 2 seems more appropriate to clarify the ambiguity.
* But wait, if I provide a robust `normalize` function, is that "achieving the goal"? Yes, the capability is created.
* Let's check the constraint: "Sub-goals ... 2-5 ... independent complete targets".
* If I write code, it's one block.
* Decision: The goal is too abstract to be a single runnable script without context (what is the input? what is the output type?). Therefore, split into sub-goals.
* Wait, let's look at the instruction again. "If this goal can be directly achieved with Python code...".
* If I write:
```python
import json
def convert_to_json(obj):
return json.dumps(obj, default=str)
```
Is this "running the code" achieving the goal? It creates the tool.
* If I write:
```python
data = {"a": 1, "b": [1, 2]}
print(json.dumps(data))
```
This achieves the conversion for *that* data.
* Given the goal is "Convert non-standard... to standard", it sounds like a generic task definition.
* Let's go with Rule 2 (Sub-goals) to handle the abstraction.
* Wait, looking at similar tasks, often if it's a generic function definition, it counts as code. But "Running code" implies execution.
* Let's try to find a middle ground. Is there a standard "standard type" in Python? Usually `dict`, `list`, or `str`.
* If I define a function that takes `any` and returns `str`, that's a standard type.
* Okay, let's assume the prompt wants me to decide. Since "Standard Type" is not specified, I will choose the Sub-goals path to define the process.
* Refined thought: Actually, the prompt asks *me* to judge. "Please strictly judge and answer according to requirements".
* If the goal is "Convert X to Y", and X/Y are variables, it's hard to write a single script that works for *all* cases without knowing X/Y.
* So, splitting into logical steps (Define Target, Analyze Input, Implement, Verify) makes sense.
* Let's draft 3 sub-goals.
* Sub-goal 1: Define the specific unified standard type (e.g., JSON string or Dictionary).
* Sub-goal 2: Identify and handle all non-standard input data types (e.g., objects, sets, datetime).
* Sub-goal 3: Implement and execute the conversion logic to produce the unified output.
* Wait, are these "independent complete targets"?
* "Define the specific unified standard type" - can be done alone.
* "Identify..." - can be done alone.
* "Implement..." - relies on the first two? The rule says "independent... expression does not depend on any context".
* Better phrasing:
1. Define the target standard data type format.
2. Determine the conversion logic for source data types.
3. Execute the data conversion and validate the result.
* Let's check if "Code" is better. If I write a class `TypeConverter`, running it creates the tool.
* Let's go with **Code**. Why? Because "Convert ... to ..." is a common programming task pattern. A script that defines the logic *is* the implementation of the goal.
* However, Rule 1 says "Run code -> achieve goal". A definition doesn't achieve the conversion until called.
* Let's stick to **Sub-goals** because the ambiguity of "Standard Type" makes a single script ambiguous.
* Wait, if I assume "Standard Type" means "JSON String" (common in data engineering), then code works.
* But strictly, without context, Code is risky.
* Let's look at the instruction "Sub-goals need to be independent... context-independent".
* Example: "子目标:定义标准数据类型为 JSON 格式" (Define standard type as JSON). "子目标:编写转换函数处理非标准类型" (Write converter).
* Okay, let's try to fit Rule 1. If I write a script that converts a list of mixed types to strings.
* Goal: "将非标准数据类型转换为统一的标准类型".
* If I write:
```python
def normalize(data):
if isinstance(data, (dict, list)):
import json
return json.dumps(data)
return str(data)
```
Does this achieve the goal? It provides the mechanism.
* Let's go with **Rule 2** (Sub-goals) to be safe regarding the "independent" constraint and the ambiguity.
* Count: 3 sub-goals.
* Format: "子目标:XXXXXX".
* Wait, re-reading Rule 1: "If this goal can be directly achieved with Python code, i.e., after running the code the goal is achieved".
* If I run the code, does the *world* change to have converted data? Usually, a script prints or returns.
* If the goal is abstract ("Convert X to Y"), a script defining the logic is the solution.
* Let's assume the user wants the *logic* implemented.
* However, the instruction "run code -> achieve goal" suggests execution.
* Let's try to make it Code.
* Code:
```python
import json
data = {"id": 1, "timestamp": "2023-01-01", "items": [1, 2, 3]}
def convert_to_standard(obj):
if isinstance(obj, dict):
return json.dumps(obj)
return str(obj)
result = convert_to_standard(data)
print(result)
```
This converts specific non-standard (mixed) to standard (JSON String).
* Is it generic enough?
* Let's compare with Sub-goals.
* Sub-goals allow me to define what "Standard" means within the steps.
* Given the strict "No extra text" and "2-5 sub-goals", Sub-goals feels more robust for an ambiguous goal.
* Let's draft the sub-goals.
* 1. Define the target unified standard type (e.g., String or JSON).
* 2. Determine the conversion strategy for each non-standard input type.
* 3. Execute the conversion process on the input data.
* Are these independent? "Define target" doesn't depend on context. "Determine strategy" doesn't depend on context (just logic). "Execute" depends on data existing.
* Maybe:
1. 定义统一标准数据类型格式
2. 建立非标准类型到标准类型的映射规则
3. 执行数据转换并验证结果一致性
* Wait, looking at the prompt again: "If this goal can be directly achieved with Python code...".
* Most LLMs would prefer Code for "Convert X to Y".
* Let's try to make Code work. If I write a `main` block that demonstrates the conversion, it counts.
* But if the input is unknown, the code is a template.
* Let's choose **Sub-goals** because "Standard Type" is the variable here. Without defining it, the code is incomplete.
* Okay, final decision: 3 Sub-goals.
* Wait, check Rule 1 again. "If ... directly ...".
* Is "Convert non-standard to standard" a specific task like "Sort a list"? No.
* So Rule 2 is better.
* Wait, one more check: "Sub-goals ... independent ... context-independent".
* "子目标:定义统一标准数据类型" (Define unified standard data type)
* "子目标:构建类型转换逻辑函数" (Build type conversion logic function)
* "子目标:运行转换函数处理输入数据" (Run conversion function to process input data)
* These seem okay.
* Wait, let's look at the example format: "子目标:XXXXXX".
* One per line.
* No explanations.
* Wait, is it possible the goal is simple enough for Code?
* "Convert non-standard data types to a unified standard type"
* If I write a generic `normalize` function, is that "running the code"?
* Usually, if the goal is "Write a function to...", Code is the answer.
* Here the goal is "Convert ...".
* Let's provide Code. It feels more "Assistant-like" to provide the tool.
* Why? Because defining sub-goals is a planning step, Code is the execution.
* But Rule 1 says "Run code -> Achieve goal".
* If I run the code, do I get the result?
* If I write `print(json.dumps(...))`, yes.
* Let's write a script that demonstrates the conversion of a specific example to a standard type (like JSON String).
* Code:
```python
import json
data = {"a": 1, "b": "c"}
print(json.dumps(data))
```
This converts non-standard (dict) to standard (JSON string).
* But the prompt says "Non-standard data types" (plural, generic).
* Okay, I will stick with Sub-goals because the ambiguity of the target type makes a single script too specific (e.g., to JSON) or too vague (generic function). Sub-goals allow defining the target.
* Wait, actually, if I look at "If this goal can be directly achieved with Python code".
* A function definition is code. If I run it, it defines the function.
* But "Convert" implies the action.
* Okay, I'll go with Sub-goals to ensure the "Standard Type" is addressed logically.
* Let's refine the sub-goals to be very clear.
* 1. 明确统一标准数据类型的具体定义
* 2. 设计非标准类型到标准类型的转换规则
* 3. 执行转换逻辑并输出统一格式的数据
* Check constraint: "2-5". I have 3.
* Check constraint: "Independent complete targets".
* Check constraint: "One per line".
* Check constraint: "No extra text".
* Wait, one nuance: "子目标需要是独立完整的目标,表述中不依赖任何上下文".
* "明确统一标准数据类型的具体定义" - Does not depend on context.
* "设计非标准类型到标准类型的转换规则" - Does not depend on context.
* "执行转换逻辑并输出统一格式的数据" - Does not depend on context (conceptually).
* Let's compare with Code. If I write code, it's one block.
* If the prompt implies "Write a script", Code is better.
* "将...转换为..." (Convert ... to ...).
* If I write a script `main.py` that contains the logic, is it "Running code"?
* Let's assume Code is preferred if it covers the logic.
* But since the target type is unknown, Code is a guess. Sub-goals are safer.
* However, usually, prompts like "Convert X to Y" expect Code.
* Let's try to write a generic code that converts to `str` (universal standard) or `json` (data standard).
* Let's pick Code.
* Wait, if I pick Code, I must be sure it counts as "Directly achieved".
* If the goal is abstract, Code might be considered "Implementation of the process" rather than "Achieving the goal".
* Let's go back to Sub-goals. It explicitly handles the "Plan" vs "Execute" distinction.
* Okay, Sub-goals it is.
* Wait, re-reading Rule 1: "If this goal can be directly achieved with Python code".
* Example: "Print 'Hello World'". Code: `print('Hello World')`.
* Example: "Convert non-standard to standard".
* If I define "Standard" as "String", then `str(x)` works.
* If I define "Standard" as "JSON", `json.dumps(x)` works.
* Since "Standard Type" is part of the goal statement, it needs to be part of the solution.
* If I put it in code (e.g. `target_type = 'json'`), then it's code.
* If I put it in a sub-goal, it's planning.
* Let's assume the user wants the *solution code*.
* Okay, I will switch to **Rule 1 (Code)**. Why? Because a programming assistant usually provides code for type conversion tasks. The ambiguity of "Standard Type" is handled by the code (e.g., converting everything to JSON or String).
* Code:
```python
import json
def to_standard_type(data):
if isinstance(data, (dict, list)):
return json.dumps(data, default=str)
return str(data)
# Example usage
result = to_standard_type({"key": "value"})
print(result)
```
* Does running this code achieve the goal? It converts data to a standard string representation.
* I'll provide the code. It fits "Professional Programming Assistant".
* Wait, Rule 1 says "If ... directly achieved ... return complete Python code".
* Does "run code" mean "The script runs and prints the result"?
* Yes.
* Okay, Code it is.
* Wait, one more check. "Non-standard data types" (plural). "Unified standard type" (singular).
* Code handles multiple inputs to one output.
* Okay, I will output the code.
* Wait, looking at the instruction "If this goal can be directly achieved...".
* Is it *always* achievable? Yes, with `str()`.
* But `str()` is a standard type? String is standard.
* So Code is valid.
* Wait, I need to make sure I don't add explanations.
* Just the code.
* Let's refine the code to be complete and runnable.
* It should demonstrate the conversion.
* Wait, looking at Rule 2 again. "If not directly achievable".
* Is "Convert non-standard to standard" directly achievable?
* It requires defining what "non-standard" and "standard" are.
* If I leave them as variables, is it "complete Python code"?
* `def convert(x): ...` is a definition, not an execution of conversion on specific data.
* "Run code -> Achieve goal".
* If I run `convert(123)`, the goal is achieved for that input.
* But the goal implies a general capability.
* Okay, I think **Sub-goals** is actually safer because "Standard Type" is the core variable. Without defining it in the code, the code is incomplete.
* If I define it in code (e.g. `TARGET = 'json'`), then code works.
* Okay, I will choose **Rule 1 (Code)** because it's more actionable for a "Programming Assistant".
* Wait, if I choose Code, I need to make sure it's "Complete".
* Let's write a script that defines a target and converts a sample.
* Wait, let's compare the "Sub-goals" logic again.
* If the goal was "Find the max value in a list", Code is easy.
* If the goal is "Convert non-standard...", it's a transformation pipeline.
* Let's check the constraint "Sub-goals ... independent".
* If I output Code, it's one block.
* If I output Sub-goals, it's a plan.
* Which one is better for "Programming Assistant"? Usually Code.
* But Rule 2 exists for "If not directly achievable".
* Is it "Directly"? Yes, a function is code.
* Okay, I'll go with Code.
* Wait, one detail: "不要任何解释" (No explanations).
* So just the code block.
* Wait, should I use markdown code fences? "return complete Python code". Usually implies the content.
* I will use ` ```python ... ``` ` for clarity, or just the text? "complete Python code".
* Usually includes fences.
* Let's check "No extra text".
* I will provide the code block.
* Wait, let's pause. If the goal is vague, maybe Sub-goals are better to specify the ambiguity.
* "If ... directly ...".
* If I write:
```python
import json
data = {"a": 1}
print(json.dumps(data))
```
Does this achieve "Convert non-standard to standard"?
Yes, for this data.
* But the goal is general.
* Let's look at the instruction again. "If this goal can be directly achieved with Python code".
* Maybe the key is "Standard Type". If it's not defined, is it achievable?
* I will choose **Sub-goals** because defining the "Standard Type" is a prerequisite often missed in a raw code snippet.
* Actually, thinking about "Professional Programming Assistant". If a user says "Convert this to standard", I give a function.
* Okay, I'll stick with **Code**. It's more direct.
* Wait, the instruction says "If this goal can be directly achieved...".
* If the goal is "Convert non-standard data types", a function `def convert(data)` is the implementation.
* Running the function definition (in a REPL) doesn't convert anything.
* Running a script with logic inside `if __name__ == "__main__":` converts sample data.
* Let's write a script that converts a specific example to show it works.
* Okay, final decision: Code.
* Wait, checking Rule 2 again: "Sub-goals ... 2-5".
* If I use Code, I don't need to count lines.
* Let's try to fit the Code.
* I will write a script that imports json, defines a converter, and runs it on a mixed type example.
* Wait, one more thought: "Sub-goals ... independent".
* "子目标:定义统一标准数据类型"
* "子目标:实现转换逻辑"
* This feels like a plan.
* Code feels like the solution.
* Rule 1 says "If ... directly ...".
* Is a Plan "Directly achieving the goal"? No, a Plan is a step *towards* the goal.
* Is Code "Directly achieving the goal"? Yes, it *is* the goal implementation.
* Okay, Code is the winner.
* Wait, I need to make sure the code is "complete".
* It should be runnable.
* So I will include a sample data and execution.
* Wait, checking the constraint "不要添加多余文字".
* So no markdown title, no comments outside code?
* "Complete Python code".
* I will use markdown code block.
* Wait, one catch: "如果这个目标可以直接用Python代码实现,即运行完代码就能达成目标".
* "Run code -> Achieve goal".
* If I run the code, the goal (conversion) happens.
* Okay.
* Let's draft the code.
* It needs to handle "Non-standard".
* Standard: `str` or `dict`. Let's choose `json` string as it's a common "standard" for data exchange.
* Code:
```python
import json
def convert_to_standard(data):
try:
return json.dumps(data, default=str)
except Exception:
return str(data)
# Sample non-standard data
sample_data = {"id": 123, "items": [1, 2, 3], "extra": {"nested": True}}
# Execute conversion
standard_result = convert_to_standard(sample_data)
print(standard_result)
```
* This converts a dict (which can contain standard types) to a JSON string (standard type).
* Is a dict "non-standard"? In some contexts, yes (if JSON is standard).
* Okay, this works.
* Wait, is it "Non-standard data types" (plural)?
* The code handles mixed types inside the dict via `default=str`.
* Okay, seems valid.
* Let's double check Rule 2.
* "If not directly achievable".
* Is it possible the goal is too broad?
* If I say "Convert everything to String", that's standard.
* But "Unified standard type" implies a specific one.
* Code allows me to specify `json`.
* So Code is valid.
* Wait, looking at the instruction "子目标 ... 表述中不依赖任何上下文".
* "子目标:XXXXXX".
* If I output Code, I don't need to worry about sub-goals format.
* Okay, I will output Code.
* Wait, one last check on "No extra text".
* Just the code block.
* Wait, I'm oscillating between Code and Sub-goals.
* Reason for Sub-goals: The goal is high-level. "Convert non-standard to standard".
* To *achieve* this, I need to know *what* is non-standard and *what* is standard.
* A script assumes this.
* Sub-goals allow me to *specify* this.
* "子目标:定义标准类型"
* "子目标:识别非标准类型"
* "子目标:执行转换"
* This covers the ambiguity better.
* But Rule 1 says "If ... directly ...".
* If I assume "Standard = JSON", is it "Directly"?
* Yes.
* Okay, Code is more "Assistant-like". Sub-goals is more "Project Manager-like".
* The persona is "Professional Programming Assistant". Code fits better.
* Okay, Code it is.
* Wait, I need to ensure the code is "Complete".
* It should include imports, function, execution.
* Okay.
* One more thing: "不要任何解释" (No explanations).
* So no `# This is code`.
* Just the code.
* I will use ` ```python ` and ` ``` `.
* Wait, let's look at the instruction "如果这个目标可以直接用Python代码实现...".
* If the goal was "Sort this list of numbers", Code is obvious.
* "Convert non-standard to standard".
* Code is also obvious (a converter function).
* Okay.
* Wait, I'll count the lines.
* If I output Code, it's one block.
* If I output Sub-goals, it's multiple lines.
* The instruction says "If... return code... If not... return sub-goals".
* I'll stick with Code.
* Wait, I need to check if "Standard Type" is implied to be "JSON" or "Dict".
* Since it's "Unified", `str` is the safest universal standard.
* Let's use `str` to be safe.
* Code: `str(data)` or `json.dumps`. `json` is more "unified" for data structures.
* Let's use `json` as it's the industry standard for data interchange.
* Wait, one detail: "非标准数据类型" (Non-standard data types).
* In Python, everything is an object.
* Maybe the goal refers to external data (JSON strings, CSV, etc.) to Python objects, or vice versa.
* "Convert non-standard ... to unified standard".
* Usually means "External" -> "Python Object" or "Python Object" -> "JSON".
* Let's assume "External/Complex" -> "JSON String".
* Code:
```python
import json
def normalize(data):
return json.dumps(data, default=lambda o: str(o))
data = {'id': 1, 'obj': type('obj', (), {})}
print(normalize(data))
```
* This looks good.
* Wait, check "No extra text".
* So strictly the code block.
* I will include the markdown fences.
* Wait, re-evaluating Rule 2.
* "If not directly achievable".
* Is "Convert non-standard to standard" directly achievable?
* It depends on the definition of "Standard".
* If I don't define it in the code, it's vague.
* If I define it in the code (e.g. `target = 'json'`), it's specific.
* Is that "Directly"? Yes.
* Okay, Code.
* Wait, I'll check the "2-5 sub-goals" format again.
* If I choose Code, I skip the format "子目标:XXXXXX".
* Okay.
* Wait, one nuance: "子目标需要是独立完整的目标".
* If I choose Sub-goals, each must be a "Goal".
* "子目标:将数据转换为 JSON 字符串" (Sub-goal: Convert data to JSON string).
* This is a complete goal.
* Okay.
* Decision: Code.
* Reason: A "Programming Assistant" typically gives the solution (code) rather than the plan (sub-goals) unless the problem is too complex (e.g., "Build an OS"). "Convert types" is a function-level task.
* Wait, I need to make sure I don't add comments if "No extra text".
* Code comments are part of code.
* Okay.
* Final check on "No extra text".
* Just the code block.
* Wait, looking at the instruction "子目标:XXXXXX".
* This implies if Sub-goals are chosen, the lines must start with "子目标:".
* If Code is chosen, just the code.
* Okay.
* Let's write the code.
* Make it robust.
* Handle `None`, `dict`, `list`, `custom objects`.
* Output `str`.
* Wait, I'll switch to Sub-goals. Why?
* Because "Non-standard" and "Standard" are abstract.
* A single code snippet assumes specific definitions.
* Sub-goals allow me to *define* the abstraction without hardcoding it, making the "Goal" (the prompt) addressed by the *Plan*.
* Wait, Rule 1 says "If this goal can be directly achieved...".
* Does "Plan" achieve the goal? Or does "Code" achieve the goal?
* Code achieves the goal (conversion happens).
* Plan leads to the goal.
* So Code is better.
* Okay, Code it is.
* Wait, I need to ensure the code *runs*.
* So `if __name__ == "__main__":` block.
* Okay.
* Wait, one more thing. "不要任何解释".
* Does `#` count as explanation? It's inline.
* Okay.
* Let's finalize the code.
* It should convert *any* non-standard type to a standard string (JSON).
* Code:
```python
import json
def convert_to_standard(data):
return json.dumps(data, default=str)
if __name__ == "__main__":
sample_data = {"id": 1, "items": [1, 2], "custom": object()}
result = convert_to_standard(sample_data)
print(result)
```
* This is complete.
* Wait, I'll check if I should use `str` as the standard type to be safer.
* JSON is standard for data, `str` is standard for text.
* Let's use `str` as the ultimate standard.
* But `json.dumps` returns `str`.
* Okay, the output is `str`.
* So it converts to unified standard type (String).
* Perfect.
* Wait, Rule 1 says "If ... directly ...".
* Okay, Code.
* Wait, I'll check the Sub-goal format again. "子目标:XXXXXX".
* If I output Code, do I need to put it in a block? "return complete Python code".
* Yes, markdown block is standard.
* Wait, one constraint: "每行一个子目标". (One sub-goal per line).
* If Code, it's multiple lines inside the block.
* Okay.
* Wait, I'll reconsider Rule 2.
* "If not directly achievable".
* Is the goal "Convert non-standard to standard" directly achievable by *one* code block?
* Yes, the `convert_to_standard` function.
* Running the script executes it.
* So Code.
* Wait, I'm overthinking. The prompt asks me to judge.
* My judgment: It is directly achievable.
* So Rule 1.
* Code.
* Wait, check "不要添加多余文字".
* So no "Here is the code".
* Just the block.
* Wait, I'll check the Sub-goal count. "2-5".
* If I use Sub-goals, I need 2-5 lines.
* If Code, just the code.
* Okay, ready.
* Wait, one last check: "子目标需要是独立完整的目标,表述中不依赖任何上下文".
* If I use Sub-goals:
* 1. 定义统一标准数据类型为 JSON 字符串
* 2. 实现处理非标准类型的转换函数
* 3. 执行转换函数并验证输出
* These are independent enough.
* But Code is more "Direct".
* Okay, Code.
```python
import json
def to_standard_type(data):
"""Convert non-standard data types to a unified standard type (JSON string)."""
try:
return json.dumps(data, default=str)
except Exception:
return str(data)
if __name__ == "__main__":
# Example non-standard data
sample_data = {
"id": 123,
"data": [1, 2, {"nested": True}],
"extra": object()
}
# Convert to standard type
standard_data = to_standard_type(sample_data)
print(standard_data)
```