📜  Python – 列表中的条件前缀

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

Python – 列表中的条件前缀

给定一个元素列表,根据条件附加不同的前缀。

方法#1:使用循环

可以执行此任务的这种粗暴方式。在此,我们使用条件运算符和循环执行附加前缀的任务。

Python3
# Python3 code to demonstrate working of
# Conditional Prefix in List
# Using loop
 
# initializing list
test_list = [45, 53, 76, 86, 3, 49]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing pref 1
pref_1 = "LOW-"
 
# initializing pref 2
pref_2 = "HIGH-"
 
res = []
for ele in test_list:
     
    # appending prefix on greater than 50 check
    if ele >= 50:
        res.append(pref_2 + str(ele))
    else :
        res.append(pref_1 + str(ele))
         
# printing result
print("The prefixed elements : " + str(res))


Python3
# Python3 code to demonstrate working of
# Conditional Prefix in List
# Using list comprehension
 
# initializing list
test_list = [45, 53, 76, 86, 3, 49]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing pref 1
pref_1 = "LOW-"
 
# initializing pref 2
pref_2 = "HIGH-"
 
# solution encapsulated as one-liner and conditional checks
res = [pref_2 + str(ele) if ele >= 50 else pref_1 + str(ele) for ele in test_list]
         
# printing result
print("The prefixed elements : " + str(res))


输出
The original list : [45, 53, 76, 86, 3, 49]
The prefixed elements : ['LOW-45', 'HIGH-53', 'HIGH-76', 'HIGH-86', 'LOW-3', 'LOW-49']

方法#2:使用列表推导

这是可以执行此任务的方式之一。在此,我们使用列表理解执行与上述类似的任务。

Python3

# Python3 code to demonstrate working of
# Conditional Prefix in List
# Using list comprehension
 
# initializing list
test_list = [45, 53, 76, 86, 3, 49]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing pref 1
pref_1 = "LOW-"
 
# initializing pref 2
pref_2 = "HIGH-"
 
# solution encapsulated as one-liner and conditional checks
res = [pref_2 + str(ele) if ele >= 50 else pref_1 + str(ele) for ele in test_list]
         
# printing result
print("The prefixed elements : " + str(res))
输出
The original list : [45, 53, 76, 86, 3, 49]
The prefixed elements : ['LOW-45', 'HIGH-53', 'HIGH-76', 'HIGH-86', 'LOW-3', 'LOW-49']