Skip to content
Advertisement

How to let if fuction output only one output in python?

I am trying to use if function to classify the items into 3 categories in python. My code is as follows.

WBS4_ELEMENT_list_0 = ['F.1122023.117.2.001', 'F.1122012.024.2.001', 'F.1622016.AET.2.001', 'F.1622015.137.2.001', 'F.1622015.034.2.001', 'F.1622032.100.2.001', 'F.1622016.040.2.001', 'F.1622016.017.1.002', 'F.1622015.084.2.001', 'F.1622015.548.1.001', 'F.1622015.918.1.001', 'F.1122012.606.2.001', 'F.1622015.311.1.007','F.1622016.091.1.013']
print(len(WBS4_ELEMENT_list_0))
WBS4_ELEMENT_list =[]
for i in WBS4_ELEMENT_list_0:
    ii=str(i)
    WBS4_ELEMENT_list.append(ii)

Child_or_Parent_based_on_WBS4_element_list = []

for h in WBS4_ELEMENT_list:
    pos = WBS4_ELEMENT_list.index(h)
    if WBS4_ELEMENT_list[pos][13:19]==".1.001":
        Child_or_Parent_based_on_WBS4_element_list.append(WBS4_ELEMENT_list[pos]+"_Parent")
    if WBS4_ELEMENT_list[pos][13:19]==".2.001":
        Child_or_Parent_based_on_WBS4_element_list.append(WBS4_ELEMENT_list[pos]+"_Facility")
    if WBS4_ELEMENT_list[pos][13:19]!=".1.001" or WBS4_ELEMENT_list[pos][13:19]!=".2.001":
        Child_or_Parent_based_on_WBS4_element_list.append(WBS4_ELEMENT_list[pos]+"_Child")

print(len(Child_or_Parent_based_on_WBS4_element_list))
print(Child_or_Parent_based_on_WBS4_element_list)

However, there are 25 outputs which is out of the range of 14 (the number of items in WBS4_ELEMENT_list_0 ). Please help me to keep if fuction output only one output in python.

Advertisement

Answer

You can do it in a cleaner and faster way by using list comprehensions and a dict:

WBS4_ELEMENT_list_0 = ['F.1122023.117.2.001', 'F.1122012.024.2.001', 'F.1622016.AET.2.001', 'F.1622015.137.2.001', 'F.1622015.034.2.001', 'F.1622032.100.2.001', 'F.1622016.040.2.001', 'F.1622016.017.1.002', 'F.1622015.084.2.001', 'F.1622015.548.1.001', 'F.1622015.918.1.001', 'F.1122012.606.2.001', 'F.1622015.311.1.007','F.1622016.091.1.013']

d = {'.1.001': '_Parent', '.2.001': '_Facility'}

Child_or_Parent_based_on_WBS4_element_list = [s + d.get(s[-6:], '_Child') for s in WBS4_ELEMENT_list_0]

Output:

['F.1122023.117.2.001_Facility', 'F.1122012.024.2.001_Facility', 'F.1622016.AET.2.001_Facility', 'F.1622015.137.2.001_Facility', 'F.1622015.034.2.001_Facility', 'F.1622032.100.2.001_Facility', 'F.1622016.040.2.001_Facility', 'F.1622016.017.1.002_Child', 'F.1622015.084.2.001_Facility', 'F.1622015.548.1.001_Parent', 'F.1622015.918.1.001_Parent', 'F.1122012.606.2.001_Facility', 'F.1622015.311.1.007_Child', 'F.1622016.091.1.013_Child']
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement