请求解决拆分List<List<double>>中连续重复数字序列的问题
Got it, let's tackle this problem head-on! Your goal is to take a List<List<double>> and split it into groups where each group holds consecutive identical sublists—like turning your sample input [[1,2,3], [1,2,3], [1,2,3], [4,5,6], ...] into [[[1,2,3], [1,2,3], [1,2,3]], [[4,5,6], ...], ...]. Here's a straightforward, practical approach:
Step-by-Step Implementation (C# Example)
This code handles edge cases, floating-point precision quirks, and follows the logic you need:
public static List<List<List<double>>> SplitConsecutiveIdenticalGroups(List<List<double>> input) { var groupedResult = new List<List<List<double>>>(); if (input == null || input.Count == 0) return groupedResult; // Start with the first sublist as our initial group var currentGroup = new List<List<double>> { input[0] }; for (int i = 1; i < input.Count; i++) { var currentSublist = input[i]; var lastInCurrentGroup = currentGroup.Last(); // Check if the current sublist matches the last one in the group // For doubles, use a small tolerance to avoid precision issues bool areSublistsEqual = currentSublist.Count == lastInCurrentGroup.Count && currentSublist.Zip(lastInCurrentGroup, (a, b) => Math.Abs(a - b) < 1e-9) .All(isEqual => isEqual); if (areSublistsEqual) { // Add to the current group if it's a match currentGroup.Add(currentSublist); } else { // Finalize the current group and start a new one groupedResult.Add(currentGroup); currentGroup = new List<List<double>> { currentSublist }; } } // Don't forget to add the last group to the result! groupedResult.Add(currentGroup); return groupedResult; }
Key Details to Keep in Mind
- Floating-Point Precision: Never use direct
==to compare doubles—tiny rounding errors can break equality checks. The code uses a tolerance of1e-9; adjust this based on how precise your data needs to be. - Edge Cases: Gracefully handles empty or null input, and ensures we don’t miss the final group after the loop finishes.
- Sublist Structure: First checks if sublists have the same length to avoid index errors and ensure we’re comparing like-for-like elements.
Quick Usage Example
Here’s how you’d test this with your sample data:
var inputList = new List<List<double>> { new() { 1, 2, 3 }, new() { 1, 2, 3 }, new() { 1, 2, 3 }, new() { 4, 5, 6 }, new() { 4, 5, 6 }, new() { 4, 5, 6 }, new() { 7, 8, 9 } }; var result = SplitConsecutiveIdenticalGroups(inputList); // Result will be three distinct groups: // Group 0: [1,2,3] repeated 3 times // Group 1: [4,5,6] repeated 3 times // Group 2: [7,8,9] once
If you’re using a different language (like Java or Python), the core logic stays identical—you just need to adjust syntax for list handling and equality checks. For Python, for example, you could use itertools.groupby with a custom key function to compare sublists (since groupby only groups consecutive elements, which is exactly what we want here).
内容的提问来源于stack exchange,提问作者Stavros

