📜  Python – 替换非最大记录

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

Python – 替换非最大记录

有时,在处理Python记录时,我们可能会遇到一个问题,即我们需要替换一个元素不是最大值的所有记录。这种问题可以在许多领域都有应用,包括日常编程和Web开发领域。让我们讨论可以执行此任务的某些方式。

方法 #1:使用循环 + map() + filter() + lambda
上述功能的组合可用于执行此任务。在此,我们使用 map() 和 filter 函数执行过滤任务,然后使用循环使用蛮力方法将值分配给非最大元素。

# Python3 code to demonstrate working of 
# Replace Non-Maximum Records
# Using loop + map() + filter() + lambda
  
# initializing list
test_list = [(1, 4), (9, 11), (4, 6), (6, 8), (9, 11)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = None 
  
# Replace Non-Maximum Records
# Using loop + map() + filter() + lambda
res = []
temp = list(filter(lambda ele: ele == max(test_list), test_list))
for ele in test_list:
    if ele not in temp:
        res.append(K)
    else :
        res.append(ele)
  
# printing result 
print("The list after replacing Non-Maximum : " + str(res)) 
输出 :
The original list is : [(1, 4), (9, 11), (4, 6), (6, 8), (9, 11)]
The list after replacing Non-Maximum : [None, (9, 11), None, None, (9, 11)]

方法 #2:使用列表理解 + map() + filter() + lambda
上述功能的组合可用于执行此任务。在此,我们使用与上述方法类似的方法执行任务,不同之处在于使用列表推导来分配 K。

# Python3 code to demonstrate working of 
# Replace Non-Maximum Records
# Using list comprehension + map() + filter() + lambda
  
# initializing list
test_list = [(1, 4), (9, 11), (4, 6), (6, 8), (9, 11)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = None 
  
# Replace Non-Maximum Records
# Using list comprehension + map() + filter() + lambda
temp = list(filter(lambda ele: ele == max(test_list), test_list))
res = [ele if ele in temp else K for ele in test_list]
  
# printing result 
print("The list after replacing Non-Maximum : " + str(res)) 
输出 :
The original list is : [(1, 4), (9, 11), (4, 6), (6, 8), (9, 11)]
The list after replacing Non-Maximum : [None, (9, 11), None, None, (9, 11)]