📌  相关文章
📜  Python程序提取具有共同差异元素的行

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

Python程序提取具有共同差异元素的行

给定一个矩阵,用 AP 序列提取行。

方法#1:使用循环

在这种情况下,我们使用循环检查所有具有共同差异的元素,如果没有发现任何元素同步,则该行被标记为关闭并且不添加到结果中。

Python3
# Python3 code to demonstrate working of 
# Extract rows with common difference elements
# Using loop
  
# initializing list
test_list = [[4, 7, 10],
             [8, 10, 12],
             [10, 11, 13], 
             [6, 8, 10]]
  
# printing original list
print("The original list is : " + str(test_list))
          
res = []
for row in test_list:
    flag = True 
    for idx in range(0, len(row) - 1):
          
        # check for common difference
        if row[idx + 1] - row[idx] != row[1] - row[0]:
            flag = False 
            break
    if flag :
        res.append(row)
  
# printing result 
print("Filtered Matrix : " + str(res))


Python3
# Python3 code to demonstrate working of 
# all() + list comprehension
# Using list comprehension + all()
  
# initializing list
test_list = [[4, 7, 10],
             [8, 10, 12],
             [10, 11, 13], 
             [6, 8, 10]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# checking for all values to have common difference         
res = [row for row in test_list
       if all(row[idx + 1] - row[idx] == row[1] - row[0]
              for idx in range(0, len(row) - 1))]
  
# printing result 
print("Filtered Matrix : " + str(res))


输出:

方法#2:使用 all() + 列表推导式

在此,我们使用 all() 检查所有值是否具有共同差异,列表理解用于执行行的迭代。

蟒蛇3

# Python3 code to demonstrate working of 
# all() + list comprehension
# Using list comprehension + all()
  
# initializing list
test_list = [[4, 7, 10],
             [8, 10, 12],
             [10, 11, 13], 
             [6, 8, 10]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# checking for all values to have common difference         
res = [row for row in test_list
       if all(row[idx + 1] - row[idx] == row[1] - row[0]
              for idx in range(0, len(row) - 1))]
  
# printing result 
print("Filtered Matrix : " + str(res))

输出: