Python列表效率:将变量批量转换为str和列表生成

时间:2014-07-24 17:31:19

标签: python-2.7

所以con只是我从我建立的日期生成器匹配的条件。此函数的所有输出都是不可变的。所以我有把这些输出转换成字符串的“很棒的”任务。原因是我想在输出中附加/前置标记。在处理大量变量时,这会非常麻烦。准确地说365天。

con0 = str(context[0])
con1 = str(context[1])
con2 = str(context[2])
con3 = str(context[3])
con4 = str(context[4])
con5 = str(context[5])
con6 = str(context[6])
con7 = str(context[7])
con8 = str(context[8])
con9 = str(context[9])
con10 = str(context[10])
con11 = str(context[11])
con12 = str(context[12])
...
con364 = str(context[364])

day0 = con0[0:10].replace("-", "");
day1 = con1[0:10].replace("-", "");
day2 = con2[0:10].replace("-", "");
day3 = con3[0:10].replace("-", "");
day4 = con4[0:10].replace("-", "");
day5 = con5[0:10].replace("-", "");
day6 = con6[0:10].replace("-", "");
day7 = con7[0:10].replace("-", "");
day8 = con8[0:10].replace("-", "");
day9 = con9[0:10].replace("-", "");
day10 = con10[0:10].replace("-", "");
day11 = con11[0:10].replace("-", "");
day12 = con12[0:10].replace("-", "");
...
day364 = con364[0:10].replace("-", "");


exclude = [ '  "/' + year0 + "/" + day0 + "*" + '"', '  "/' + year0 + "/" + day1 + "*" + '"', '  "/' + year0 + "/" + day2 + "*" + '"', '  "/' + year0 + "/" + day3 + "*" + '"', '  "/' + year0 + "/" + day4 + "*" + '"', '  "/' + year0 + "/" + day5 + "*" + '"', '  "/' + year0 + "/" + day6 + "*" + '"', '  "/' + year0 + "/" + day7 + "*" + '"', '  "/' + year0 + "/" + day8 + "*" + '"', '  "/' + year0 + "/" + day9 + "*" + '"', '  "/' + year0 + "/" + day10 + "*" + '"', '  "/' + year0 + "/" + day11 + "*" + '"', '  "/' + year0 + "/" + day12 ... + year0 + "/" + day364 + "*" + '"' ]

d0 = '  "*%s*"\n' % (day0)
y0 = '  "/%s/*"\n' % (year0)
w0 = '  %s\n''  %s\n''  %s\n''  %s\n''  %s\n''  %s\n''  %s\n''  %s\n''  %s\n''  %s\n''  %s\n''  %s\n''  %s\n' % (exclude[7],exclude[8],exclude[9],exclude[10],exclude[11],exclude[12]....exclude[364])

是否有更多pythonic方法可以使批量字符串替换和生成列表比使用我的for i bash循环为我构建它们更容易?

1 个答案:

答案 0 :(得分:1)

当你有许多变量都以数字结尾时,这是一个很好的信号,表明你应该使用单个列表。您可以使用列表推导来简明地构建列表。

cons = [str(context[i]) for i in range(365)]
days = [con[0:10].replace("-", "") for con in cons]
exclude = ['  "/{}/{}*"'.format(year0, day) for day in days]
w0 = "\n".join("  " + day for for day in days)