You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 0 first (cleaner and more efficient).
  • If you prefer lists over tuples for the output, just replace tuple() with list() in the deduplication steps.
  • Feel free to re-add the math or numpy imports if you need them for other parts of your project.

内容的提问来源于stack exchange,提问作者PixelPrime

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:02:29