Python:如何结合一维列表去重代码与用户输入二维列表代码实现每行去重?
Combine 2D Input with Per-Row Deduplication
Let's break down how to merge your two code snippets to deduplicate each row of your 2D list. Here's a step-by-step solution tailored to your existing code:
1. Basic Combined Code (Using Set for Deduplication)
First, we'll retain your 2D input logic, then apply your 1D deduplication approach to each individual row. Note that using set() will remove duplicates but lose the original order of elements in the row:
# Removed unused imports (math/numpy) since they aren't needed for this logic m = int(input("rows: ")) n = int(input("columns: ")) print("\nEnter words:\n") # Build the 2D list from user input (simplified from your original code) twodlist = [] for i in range(m): current_row = [] for j in range(n): element = input() current_row.append(element) twodlist.append(current_row) # Apply deduplication to each row using your set-based method deduplicated_result = [] for row in twodlist: dedup_row = tuple(set(row)) deduplicated_result.append(dedup_row) # Print the final output print("\nDeduplicated 2D List (each row is a tuple):") for row in deduplicated_result: print(row)
2. Preserve Element Order (If Needed)
If you want to keep the order of the first occurrence of each element in the row, replace the set-based deduplication with a custom function that tracks seen elements:
def deduplicate_preserve_order(lst): seen = set() ordered_result = [] for item in lst: if item not in seen: seen.add(item) ordered_result.append(item) return tuple(ordered_result) # Update the deduplication loop to use this function deduplicated_result = [] for row in twodlist: dedup_row = deduplicate_preserve_order(row) deduplicated_result.append(dedup_row)
Quick Notes:
- I simplified your original 2D input code to directly build rows without initializing with
0first (cleaner and more efficient). - If you prefer lists over tuples for the output, just replace
tuple()withlist()in the deduplication steps. - Feel free to re-add the
mathornumpyimports if you need them for other parts of your project.
内容的提问来源于stack exchange,提问作者PixelPrime
相关产品推荐
相关产品推荐

