不止热门角色,我们为你扩展了更多细分角色分类,覆盖职场提升、商业增长、内容创作、学习规划等多元场景。精准匹配不同目标,让每一次生成都更有方向、更高命中率。
立即探索更多角色分类,找到属于你的增长加速器。
{
"code": "[x**2 for x in range(10)]",
"description": "该代码使用列表推导式生成一个包含0至9之间数字的平方的列表。列表推导式提供了一种简洁、高效的方式来创建列表。",
"examples": [
"# 使用列表推导式生成一个平方列表",
"squared_numbers = [x**2 for x in range(10)]",
"print(squared_numbers) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]"
],
"language": "Python",
"complexity": 1
}
以下是生成的符合要求的JSON格式代码片段:
{
"code": "import requests\n\ndef make_api_request(url, method=\"GET\", payload=None, headers=None):\n \"\"\"\n Makes an API request to the specified URL using the given method, payload, and headers.\n\n :param url: API endpoint URL (str)\n :param method: HTTP method (default is \"GET\", can be \"POST\", \"PUT\", \"DELETE\", etc.) (str)\n :param payload: Data to send with the request (default is None) (dict)\n :param headers: Custom headers for the request (default is None) (dict)\n :return: Response object from the API request\n \"\"\"\n try:\n if method.upper() == \"GET\":\n response = requests.get(url, headers=headers)\n elif method.upper() == \"POST\":\n response = requests.post(url, json=payload, headers=headers)\n elif method.upper() == \"PUT\":\n response = requests.put(url, json=payload, headers=headers)\n elif method.upper() == \"DELETE\":\n response = requests.delete(url, headers=headers)\n else:\n raise ValueError(\"Unsupported HTTP method: {}\".format(method))\n\n # Raise exception for HTTP errors\n response.raise_for_status()\n return response\n except requests.exceptions.RequestException as e:\n print(f\"An error occurred: {e}\")\n return None",
"description": "This Python function allows users to make HTTP API requests (GET, POST, PUT, DELETE) with optional payloads and headers. It ensures proper error handling and supports raising exceptions for HTTP errors.",
"examples": [],
"language": "Python",
"complexity": 2
}
{
"code": "import pandas as pd\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\n\ndef preprocess_data(data, numeric_features, categorical_features):\n \"\"\"\n Preprocess the dataset by handling numeric and categorical features separately.\n\n Args:\n data (pd.DataFrame): The input dataset as a pandas DataFrame.\n numeric_features (list): List of column names corresponding to numeric features.\n categorical_features (list): List of column names corresponding to categorical features.\n\n Returns:\n pd.DataFrame: Transformed dataset with numeric features scaled and categorical features one-hot encoded.\n \"\"\"\n # Define a pipeline for numeric features\n numeric_transformer = Pipeline(steps=[\n ('scaler', StandardScaler())\n ])\n\n # Define a pipeline for categorical features\n categorical_transformer = Pipeline(steps=[\n ('onehot', OneHotEncoder(handle_unknown='ignore'))\n ])\n\n # Combine preprocessors in a column transformer\n preprocessor = ColumnTransformer(\n transformers=[\n ('num', numeric_transformer, numeric_features),\n ('cat', categorical_transformer, categorical_features)\n ]\n )\n\n # Fit transform the data\n processed_data = preprocessor.fit_transform(data)\n\n # Convert the processed result back to a DataFrame\n numeric_columns = numeric_features\n categorical_columns = preprocessor.named_transformers_['cat']['onehot'].get_feature_names_out(categorical_features)\n all_columns = list(numeric_columns) + list(categorical_columns)\n\n return pd.DataFrame(processed_data, columns=all_columns)\n",
"description": "该代码实现了数据预处理功能,其中包括对数值特征的标准化(StandardScaler)与分类特征的独热编码(OneHotEncoder)。它使用ColumnTransformer结合两个管道分别处理数值和分类特征。",
"examples": [
"import pandas as pd\n\n# Original dataset\ndata = pd.DataFrame({\n 'age': [25, 32, 47],\n 'salary': [50000, 80000, 120000],\n 'gender': ['male', 'female', 'male'],\n 'state': ['NY', 'CA', 'TX']\n})\n\n# Define features\nnumeric_features = ['age', 'salary']\ncategorical_features = ['gender', 'state']\n\n# Call the preprocessing function\nprocessed_data = preprocess_data(data, numeric_features, categorical_features)\n\n# Check processed data\nprint(processed_data.head())",
"import numpy as np\n\n# Another example with missing values\ndata_with_nan = pd.DataFrame({\n 'age': [np.nan, 29, 41],\n 'salary': [45000, 95000, 110000],\n 'gender': ['female', 'male', None],\n 'state': ['FL', 'NV', 'TX']\n})\n\nprocessed_data_with_nan = preprocess_data(data_with_nan, numeric_features, categorical_features)\n\nprint(processed_data_with_nan)"
],
"language": "Python",
"complexity": 3
}
帮助用户通过简单输入关键字,即可快速生成高质量、精准的Python代码片段,适应学习、开发和问题解决场景,从而显著提升开发效率,降低学习与实践门槛。