其他方法为循环执行此操作?

时间:2018-03-20 08:20:27

标签: python string for-loop replace split

我只是想知道是否有办法改进这个循环,如果以某种方式跳过那些。

Var String可以有更多参数,它们的顺序可以是随意的 为了用真实值替换参数,我需要:

  1. 拆分
  2. 检查参数是什么以及在哪个位置
  3. 以下是我如何思考的合成示例:

    String = "{FullDate}_{Month}_{Day}_{Year}_{ElementID}_{ElementCD}"
    String_split = String.split("_")
    
    for params in range(len(String_split)):
    
        if "FullDate" in String_split[params]:
            # Do something
        elif "Name" in String_split[params]:
            # Do something
        elif "ElementID" in String_split[params]:
            # Do something
        elif "ElementCD" in String_split[params]:
            # Do something
        elif "Year" in String_split[params]:
            # Do something
        elif "Day" in String_split[params]:
            # Do something
        elif "Month" in String_split[params]:
            # Do something
    

    更新:这就是我想要完成的事情

    # Default values
    FullDate = now().format("yyyy-MM-dd_HH:mm:ss")
    Name = "John"
    ElementID = "Apple"
    ElementCD = "01Appxz"
    Year = now().format("yyyy")
    Day = now().format("dd")
    Month = now().format("MM")
    ############################
    
    String = "{FullDate}_{Month}_{Day}_{Year}_{ElementID}_{ElementCD}"
    String_split = String.split("_")
    
    for params in range(len(String_split)):
    
        if "FullDate" in String_split[params]:
            Report_Name = Report_Name + FullDate + "_"
        elif "Name" in String_split[params]:
            Report_Name = Report_Name + Name + "_"
        elif "ElementID" in String_split[params]:
            Report_Name = Report_Name + ElementID + "_"
        elif "ElementCD" in String_split[params]:
            Report_Name = Report_Name + ElementCD + "_"
        elif "Year" in String_split[params]:
            Report_Name = Report_Name + Year + "_"
        elif "Day" in String_split[params]:
            Report_Name = Report_Name + Day + "_"
        elif "Month" in String_split[params]:
            Report_Name = Report_Name + Month + "_"
    
    # Report_Name must return default values, ordered by String variable (eg: FullDate, 1st position; Month 2nd position etc..)
    # >> "1999-01-01_10:10:29_01_01_1999_Apple_01Appxz"
    # if the String variable changes the params order to
    # String = "{Year}_{Month}_{ElementCD}_{FullDate}_{ElementID}_{Day}"
    # Report_Name should return
    # >> "1999_01_01Appxz_1999-01-01_10:10:29_Apple_01"
    

2 个答案:

答案 0 :(得分:0)

  • 使用for name in names删除所有String_split[params]噪音。
  • 从变量中删除{},以便您可以使用==而不是in
  • 使用+=

这得到:

names = "FullDate Month Day Year ElementID ElementCD".split()
for name in names:
    if "FullDate" == name:
        Report_Name += FullDate + "_"
    elif "Name" == name:
        Report_Name += Name + "_"
    elif "ElementID" == name:
        Report_Name += ElementID + "_"
    elif "ElementCD" == name:
        Report_Name += ElementCD + "_"
    elif "Year" == name:
        Report_Name += Year + "_"
    elif "Day" == name:
        Report_Name += Day + "_"
    elif "Month" == name:
        Report_Name += Month + "_"

您还应该学习如何使用格式字符串和**运算符。如果您将FullDate内容更改为字典,则可以使用:

REPORT_FORMAT = '{FullDate}_{Month}_{Day}_{Year}_{ElementID}_{ElementCD}'

report = {
    'FullDate': now().format("yyyy-MM-dd_HH:mm:ss")
    'Name': "John"
    'ElementID': "Apple"
    'ElementCD': "01Appxz"
    'Year': now().format("yyyy")
    'Day': now().format("dd")
    'Month': now().format("MM")
}
report_name = REPORT_FORMAT.format(**report)

答案 1 :(得分:-1)

阅读前
  - 正如您所提到的,这是一个不使用字典

的解决方案

<强>解决方案

使用:

#Default values
FullDate = '2010-01-01_00:00:00'
Name = "John"
ElementID = "Apple"
ElementCD = "01Appxz"
Year = '2010'
Day = '01'
Month = '01'
#--

String = "{FullDate}_{Month}_{Day}_{Year}_{ElementID}_{ElementCD}"

您可以在没有for循环的情况下执行此操作,只需根据需要进行替换:

Report_Name = '.RName_' + String
if "FullDate" in Report_Name:
    Report_Name = Report_Name.replace('{FullDate}',FullDate)
if "Name" in Report_Name:
    Report_Name = Report_Name.replace('{Name}',Name)
#...
if "ElementCD" in Report_Name:
    Report_Name = Report_Name.replace('{ElementCD}',ElementCD)

print(Report_Name)
.RName_2010-01-01_00:00:00_..._01Appxz

[小心]另一种解决方案

或许您可以使用.eval()(请参阅documentation)从名称中评估变量。它要求parametersvariables名称相同 这是一种方法:

import re
Parameters = [re.sub('[{-}]+', '', s) for s in String.split('_')]

Report_Name = '.RName_' + String
for p in Parameters:
    Report_Name = Report_Name.replace('{%s}'%p,eval(p))

print(Report_Name)
.RName_2010-01-01_00:00:00_01_01_2010_Apple_01Appxz

请注意,您应谨慎使用.eval() - see Why is using eval a bad practice
检查此解决方案的替代方案 - 例如using globals/locals/vars - 如果:

  • 您想要类似的行为
  • 您认为对您的问题不够安全