I am trying to use if function to classify the items into 3 categories in python. My code is as follows.
JavaScript
x
21
21
1
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']
2
print(len(WBS4_ELEMENT_list_0))
3
WBS4_ELEMENT_list =[]
4
for i in WBS4_ELEMENT_list_0:
5
ii=str(i)
6
WBS4_ELEMENT_list.append(ii)
7
8
Child_or_Parent_based_on_WBS4_element_list = []
9
10
for h in WBS4_ELEMENT_list:
11
pos = WBS4_ELEMENT_list.index(h)
12
if WBS4_ELEMENT_list[pos][13:19]==".1.001":
13
Child_or_Parent_based_on_WBS4_element_list.append(WBS4_ELEMENT_list[pos]+"_Parent")
14
if WBS4_ELEMENT_list[pos][13:19]==".2.001":
15
Child_or_Parent_based_on_WBS4_element_list.append(WBS4_ELEMENT_list[pos]+"_Facility")
16
if WBS4_ELEMENT_list[pos][13:19]!=".1.001" or WBS4_ELEMENT_list[pos][13:19]!=".2.001":
17
Child_or_Parent_based_on_WBS4_element_list.append(WBS4_ELEMENT_list[pos]+"_Child")
18
19
print(len(Child_or_Parent_based_on_WBS4_element_list))
20
print(Child_or_Parent_based_on_WBS4_element_list)
21
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
:
JavaScript
1
6
1
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']
2
3
d = {'.1.001': '_Parent', '.2.001': '_Facility'}
4
5
Child_or_Parent_based_on_WBS4_element_list = [s + d.get(s[-6:], '_Child') for s in WBS4_ELEMENT_list_0]
6
Output:
JavaScript
1
2
1
['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']
2