Python|如果大于 n,则从元组列表中删除元组
给定一个元组列表,任务是从列表中删除所有元组,如果它大于n (比如 100)。让我们讨论一些相同的方法。
方法 #1:使用 lambda
# Python code to demonstrate
# to remove the tuples
# if certain criteria met
# initialising _list
ini_tuple = [('b', 100), ('c', 200), ('c', 45),
('d', 876), ('e', 75)]
# printing iniial_tuplelist
print("intial_list", str(ini_tuple))
# removing tuples for condition met
result = [i for i in ini_tuple if i[1] <= 100]
# printing resultant tuple list
print ("Resultant tuple list: ", str(result))
输出:
intial_list [(‘b’, 100), (‘c’, 200), (‘c’, 45), (‘d’, 876), (‘e’, 75)]
Resultant tuple list: [(‘b’, 100), (‘c’, 45), (‘e’, 75)]
方法 #2:使用过滤器 + lambda
# Python code to demonstrate
# to remove the tuples
# if certain criteria met
# initialising _list
ini_tuple = [('b', 100), ('c', 200), ('c', 45),
('d', 876), ('e', 75)]
# printing iniial_tuplelist
print("intial_list", str(ini_tuple))
# removing tuples for condition met
result = list(filter(lambda x: x[1] <= 100, ini_tuple))
# printing resultant tuple list
print ("Resultant tuple list: ", str(result))
输出:
intial_list [(‘b’, 100), (‘c’, 200), (‘c’, 45), (‘d’, 876), (‘e’, 75)]
Resultant tuple list: [(‘b’, 100), (‘c’, 45), (‘e’, 75)]
方法#3:使用朴素方法
# Python code to demonstrate
# to remove the tuples
# if certain criteria met
# initialising _list
ini_tuple = [('b', 100), ('c', 200), ('c', 45),
('d', 876), ('e', 75)]
# printing iniial_tuplelist
print("intial_list", str(ini_tuple))
# removing tuples for condition met
result = []
for i in ini_tuple:
if i[1] <= 100:
result.append(i)
# printing resultant tuple list
print ("Resultant tuple list: ", str(result))
输出:
intial_list [(‘b’, 100), (‘c’, 200), (‘c’, 45), (‘d’, 876), (‘e’, 75)]
Resultant tuple list: [(‘b’, 100), (‘c’, 45), (‘e’, 75)]