Scala中对比两个列表并生成目标字符串的实现方法
Solution to Generate Structured String from Input Columns and Data
Let's break this down—assuming you want a structured output (like a CSV-style string, a common use case here) where we use InputColumns as headers, and each entry in InputData becomes a row with values aligned to the headers (filling blanks for columns that don't have data in the map). If you need a different format (like JSON lines, tab-separated, etc.), the core logic can be adapted easily.
Step-by-Step Approach
- First, translate your pseudocode into concrete syntax (we'll use Python here since it’s perfect for handling lists and dictionaries)
- Create a header string by joining all
InputColumnswith your desired separator (e.g., comma for CSV) - For each map in
InputData, iterate throughInputColumnsin order: fetch the value for each column, or use an empty string if the column isn’t present in the map - Join each row’s values with the same separator, then combine all rows with line breaks
Python Implementation Code
# Define input data (matching your original structure) InputColumns = ["col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8", "col9", "col10", "col11", "col12", "col13"] InputData = [ {"col2": "dummy string", "col7": "2016-01-01", "col11": "2011-01-01"}, {"col2": "dummy string", "col7": "2018-01-01", "col11": "2018-01-01"}, {"col2": "dummy string", "col7": "2018-04-01", "col11": "2018-04-01"}, {"col2": "dummy string", "col7": "2016-01-01", "col11": "2016-01-01"} ] # Choose your separator (swap to "\t" for tabs, "|" for pipes, etc.) separator = "," # Build the header line header = separator.join(InputColumns) # Build each data row rows = [] for data_map in InputData: # Safely get values (empty string if column is missing) row_values = [data_map.get(col, "") for col in InputColumns] rows.append(separator.join(row_values)) # Combine header and rows into the final string final_output = f"{header}\n" + "\n".join(rows) # Use or print the result print(final_output)
Key Details
- The
get(col, "")method prevents errors when a column isn’t present in a map—it just fills in a blank instead - You can tweak the
separatorto match any format you need (e.g., tab-separated values for spreadsheet imports) - The final string will have headers as the first line, followed by each data row perfectly aligned to the columns
Alternative Format Example (Human-Readable Entries)
If you want a more descriptive string instead of a table, use this variation:
alternative_output = [] for entry_num, data_map in enumerate(InputData, 1): entry_lines = [f"Entry {entry_num}:"] + [f"- {col}: {val}" for col, val in data_map.items()] alternative_output.append("\n".join(entry_lines)) final_alt_output = "\n\n".join(alternative_output) print(final_alt_output)
This will output a list of entries with clear key-value pairs for each piece of data.
内容的提问来源于stack exchange,提问作者Curious_Bop
相关产品推荐
相关产品推荐

