首页 > 解决方案 > 如何按二维列表中的每一列查找重复元素?

问题描述

import random

A = ['a', 'b', 'c', 'd', 'e']
B = []

count = 1 
while True :
    B.append(random.choice(A))
    print(B)
    repeat = B.count('a')
    if repeat >= 2 :
        print("Waring!!!")
    if count >= 10 :
        break
    count += 1

我写了上面的代码。但我想添加一些选项。

  1. 我想将 B 创建为具有 5 行的二维列表。例如,如果计数为 6,则代码可以打印 B = [[a, b, c, a, b], [e]]
  2. 如果每列中出现两次或更多次的字母,我想打印一条警告消息。例如,如果 B = [[a, b, c, a, b], [e]] 在计数 6 中,代码将打印“警告,a,b 在 1 列中重复”。或者如果 B = [[a, b, c, a, b], [e, e, a, d, e]] 在计数 10 中,代码将打印 'Warning, a, b duplicated in 1 column' 和 'Waring , e 在 2 列中重复。'。

我一直很感激你的帮助。

标签: pythonlist

解决方案


import random
from collections import defaultdict

A = ['a', 'b', 'c', 'd', 'e']

def detect_duplicates(row, row_index):
    duplicates = defaultdict(int)
    for e in row:
        duplicates[e] += 1
    duplicates = dict(filter(lambda x: x[1] > 1, duplicates.items()))
    for e in duplicates:
        print(f'Warning, {e} duplicate in {row_index} column')

def generate_2d(total_size, row_size):
    result = []
    row_count = total_size // row_size
    tail = total_size % row_size

    for i in range(row_count):
        row = random.choices(A, k=row_size)
        detect_duplicates(row, i)
        result.append(row)
    
    if tail:
        row = random.choices(A, k=tail)
        detect_duplicates(tail, row_count+1)
        result.append(tail)
    
    return result

B = generate_2d(total_size=6, row_size=5)

推荐阅读