在python中,我试图使用if函数将项目分为3类。我的代码如下。
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)
但是,有25项输出超出了14项的范围( WBS4_ELEMENT_list_0
中的项目数)。请帮助我保持如果函数输出只有一个输出在python。
发布于 2022-08-24 18:22:25
通过使用list comprehensions
和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]
输出:
['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']
https://stackoverflow.com/questions/73481162
复制相似问题