求助:如何将下一行指定值追加到当前行末尾?
Solution to Append Next Row's Timestamp to Current Row
Got it, let's break this down and fix your problem. You need to take each row in your dataset, append the last timestamp value from the next row to its end, and handle the final row with a truncated timestamp as shown. Here's a straightforward Python implementation that does exactly this:
Step-by-Step Code Implementation
# Your original input data original_data = [ ['DDD1', 'EEE1', 'AAA1', '1516988948227'], ['DDD2', 'EEE2', 'AAA2', '1516988948076'], ['DDD3', 'EEE3', 'AAA3', '1516990485713'], ['DDD4', 'EEE4', 'AAA4', '1516990487782'] ] # Initialize an empty list to store the transformed result transformed_data = [] # Process all rows except the last one for idx in range(len(original_data) - 1): # Make a copy of the current row to avoid modifying the original data current_row = original_data[idx].copy() # Append the last element (timestamp) from the next row current_row.append(original_data[idx + 1][-1]) transformed_data.append(current_row) # Handle the final row (truncate the timestamp as in your example) final_row = original_data[-1].copy() # Truncate the timestamp to the first 7 characters plus "..." final_row[-1] = f"{final_row[-1][:7]}..." transformed_data.append(final_row) # Print the result to verify for row in transformed_data: print(row)
What This Code Does
- Preserves Original Data: We use
.copy()for each row so your original dataset stays untouched. - Appends Next Timestamp: For every row except the last, we grab the timestamp from the row immediately after it and add it to the current row's end.
- Truncates Final Timestamp: The last row's timestamp is shortened to match your example output (you can adjust the
[:7]slice if you want a longer/shorter prefix).
Output Result
When you run the code, you'll get exactly the output you're looking for:
['DDD1', 'EEE1', 'AAA1', '1516988948227', '1516988948076'] ['DDD2', 'EEE2', 'AAA2', '1516988948076', '1516990485713'] ['DDD3', 'EEE3', 'AAA3', '1516990485713', '1516990487782'] ['DDD4', 'EEE4', 'AAA4', '1516990...']
If you don't want to truncate the last row's timestamp, just replace the final row handling code with transformed_data.append(original_data[-1]) instead.
内容的提问来源于stack exchange,提问作者Iriel
相关产品推荐
相关产品推荐

