📌  相关文章
📜  Python - 将周围元素转换为 K

📅  最后修改于: 2022-05-13 01:55:01.505000             🧑  作者: Mango

Python - 将周围元素转换为 K

给定 Matrix,从每一行获取 K 的周围元素(如果存在)。

方法#1:使用index() + loop + try/except

在这里,我们使用 index() 检查元素的索引,然后通过访问下一个和上一个元素来获取所需的周围元素。如果该元素不存在,则返回一个空列表。

Python3
# Python3 code to demonstrate working of 
# Surrounding elements to K
# Using index() + loop + try/except
  
# initializing list
test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 6
  
res = []
for sub in test_list:
      
    # getting index 
    try :
        idx = sub.index(K)
    except Exception as e :
        res.append([])
        continue
      
    # appending Surrounding elements
    if idx != 0 and idx != len(sub) - 1:
        res.append([sub[idx - 1], sub[idx + 1]])
    elif idx == 0:
        res.append([sub[idx + 1]])
    else : res.append([sub[idx - 1]])
  
# printing result 
print("The Surrounding elements : " + str(res))


Python3
# Python3 code to demonstrate working of
# Surrounding elements to K
# Using index() + in operator + loop
  
# initializing list
test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 6
  
res = []
for sub in test_list:
  
    # getting index
    # checking for element presence in row
    if K in sub:
        idx = sub.index(K)
    else:
        res.append([])
        continue
  
    # appending Surrounding elements
    if idx != 0 and idx != len(sub) - 1:
        res.append([sub[idx - 1], sub[idx + 1]])
    elif idx == 0:
        res.append([sub[idx + 1]])
    else:
        res.append([sub[idx - 1]])
  
# printing result
print("The Surrounding elements : " + str(res))


输出:

方法#2:使用 index() + in 运算符 + loop

在这里,我们在应用 index() 之前检查元素是否存在于一行中,以避免使用 try/except 块。其余所有功能与上述方法相同。

蟒蛇3

# Python3 code to demonstrate working of
# Surrounding elements to K
# Using index() + in operator + loop
  
# initializing list
test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 6
  
res = []
for sub in test_list:
  
    # getting index
    # checking for element presence in row
    if K in sub:
        idx = sub.index(K)
    else:
        res.append([])
        continue
  
    # appending Surrounding elements
    if idx != 0 and idx != len(sub) - 1:
        res.append([sub[idx - 1], sub[idx + 1]])
    elif idx == 0:
        res.append([sub[idx + 1]])
    else:
        res.append([sub[idx - 1]])
  
# printing result
print("The Surrounding elements : " + str(res))

输出: