python - 如何按二维列表中的每一列查找重复元素?
问题描述
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
我写了上面的代码。但我想添加一些选项。
- 我想将 B 创建为具有 5 行的二维列表。例如,如果计数为 6,则代码可以打印 B = [[a, b, c, a, b], [e]]
- 如果每列中出现两次或更多次的字母,我想打印一条警告消息。例如,如果 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 列中重复。'。
我一直很感激你的帮助。
解决方案
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)
推荐阅读
- reactjs - 如何从 React 中的表单组件更新其他组件状态
- blazor - 如何通过渲染树构建器添加 navlink 事件处理程序?
- python-3.x - 正则表达式从地址中提取邮政编码
- java - Android studio : 安装没有成功。无法安装应用程序:INSTALL_FAILED_OLDER_SDK
- javascript - 高图表数据表未按范围选择器过滤数据
- tensorflow - Tensorflow 如何使用多个 GPU 进行单独训练?
- grpc - 如何为 gRPC 创建和使用自定义传输通道?
- javascript - 与图例 D3.js 分组条形图的交互
- sql - 选择距当前日期最多两天的列 [SQLite3]
- objective-c - macOS:使用父窗口移动子窗口时出现问题