如何按字符数对关联的SheetNameCol集合排序并维持对应关系?
Solution to Sort Sheet Names by Character Count (With Associated Header Rows)
Got it, let's solve this problem where you need to sort your sheet names by their character count while keeping the corresponding header row numbers linked. Here are two straightforward approaches depending on the tool you're using:
Excel/Google Sheets Method
This is the simplest way if you're working directly in a spreadsheet:
- Add a helper column: Insert a new column next to your
SheetNameCol(e.g., column C if sheet names are in column B). In the first data row of this helper column, enter=LEN(B2)to calculate the character count of the sheet name. Drag the formula down to apply it to all rows. - Sort the dataset: Select all your data (including the helper column), then navigate to the "Data" tab and choose "Sort". Set the primary sort key to the helper column (ascending order, so shorter names appear first). For ties (like "Act" and "Les", both 3 characters), add a secondary sort by
SheetNameColto keep them in alphabetical order if needed. - Clean up: Once sorted, you can delete the helper column if it's no longer needed.
Your sorted result will look like this:
| Index | SheetNameCol | HeaderRowCol |
|---|---|---|
| 1 | Act | 8 |
| 2 | Les | 9 |
| 3 | Act Collection | 7 |
Python (Pandas) Method
If you prefer scripting or have larger datasets to handle, pandas makes this task quick and repeatable:
First, install pandas if you haven't already:
pip install pandas
Then use this code snippet:
import pandas as pd # Initialize your dataset data = { 'Index': [1, 2, 3], 'SheetNameCol': ['Act Collection', 'Act', 'Les'], 'HeaderRowCol': [7, 8, 9] } df = pd.DataFrame(data) # Sort by character length of sheet names, then alphabetically to break ties df_sorted = df.sort_values( by=[df['SheetNameCol'].str.len(), 'SheetNameCol'], ascending=[True, True] ) # Reset the index column to match the sorted order df_sorted = df_sorted.reset_index(drop=True) df_sorted['Index'] = df_sorted.index + 1 # Print or export the sorted data print(df_sorted)
Running this will output:
Index SheetNameCol HeaderRowCol 0 1 Act 8 1 2 Les 9 2 3 Act Collection 7
内容的提问来源于stack exchange,提问作者Student of the Digital World
相关产品推荐
相关产品推荐

