簡體   English   中英

Python 3-查找同一列,同一行或兩者都不存在的字母

[英]Python 3 - Finding letters in same column, row or neither

grid = ['ABC', 'DEF', 'GHI']

我有一個類似的信件清單:

list = ['AD', 'GH', 'IC']

例如,AD在同一列中,GH在同一行中,IC都不在同一列中。 我該如何格式化檢查每個循環的循環?

您可以先建立一個從chars(row, col)

>>> table = {c:(i,j) for i, row in enumerate(grid) 
                     for j, c in enumerate(row)}
>>> table
{'A': (0, 0),
 'B': (0, 1),
 'C': (0, 2),
 'D': (1, 0),
 'E': (1, 1),
 'F': (1, 2),
 'G': (2, 0),
 'H': (2, 1),
 'I': (2, 2)}

現在很容易檢查相同的列/行:

def same_row(x, table):
    c1, c2 = x
    return table[c1][0] == table[c2][0]

def same_column(x, table):
    c1, c2 = x
    return table[c1][1] == table[c2][1]

def neither(x, table):
    return (not same_column(x, table)) and (not same_row(x, table))

一些檢查:

>>> same_column('AD', table)
True
>>> same_row('GH', table)
True
>>> same_row('IC', table)
False
>>> neither('IB', table)
True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM