[英]How do i pick a specific item in a row that has the same corresponding value with the column list - Pandas Pyhton
[英]How do a check if a column or row in a nested list has the same string
我需要檢查嵌套列表是否有具有相同字符串的列
grid = [
["x", " ", "x"],
["x", " ", " "],
["x", "x", "x"]
]
#if grid has a column or row with the same string (such as the first column and last row) then it will say "yes"
我只設法為行做到這一點:
grid = [
["x", " ", "x"],
["x", " ", " "],
["x", " ", "x"]
]
print(grid)
row = ['x', 'x', 'x']
if row in grid:
print("Yes")
else:
print("no")
執行您需要的一種簡單方法是轉置主網格以檢查列,如下所示:
gridTranspose = list(zip(*grid))
這將基本上反轉網格中的行和列。
接下來,將您的列另存為一行(例如)
如果您的網格是:
[ 1 1 0 ]
只需以相同的方式創建變量(列 = [1, 1, 0])
那么它應該工作!
-1
表示不一樣
grid = [
["x", " ", "x"],
["x", " ", " "],
["x", "x", "x"]
]
row_same = [index if all(map(lambda x: x==i[0], i)) else -1 for index, i in enumerate(grid)]
#[-1, -1, 2]
column_same = [j if all(map(lambda x: x==grid[0][j], [i[j] for i in grid])) else -1 for j in range(len(grid[0]))]
#[0, -1, -1]
我有一個簡單易懂的解決方案。
因此,基本思想是獲取行列表並創建新的列列表,然后在它們之間進行檢查 -
num = range(len(grid)) # Just an extra var, so that it is readable
lst_of_columns = [[grid[j][i] for j in num] for i in num]
# This makes a list of columns. Take it slow, print it and understand the logic
for i in num: # These lines check if rows and columns are same
for j in num:
if grid[i] == lst_of_columns[j]: # grid[i] = row 1,2,3...
print('yes') # lst_of_columns[j] = columns 1,2,3
else:
print('no')
我希望你明白這背后的邏輯。 此外,這適用於任意數量的行和列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.