example = ['1 Hey this is the first (1) level.\n', '2 This is what we call a second level.\n','','3 This is the third (3) level, deal with it.']
example = [i.rstrip() for i in example]
dictHeaders = [['1 ','One'],
['2 ','Two'],
['3 ','Three'],
['4 ','Four'],
['5 ','Five'],
['6 ','Six']]
example = [eachLine.replace(old,new,1) if eachLine.startswith(old) for eachLine in article for old, newFront in dictHeaders]
我需要它返回...
example = ['One Hey this is the first (1) level.', 'Two This is what we call a second level.','','Three This is the third (3) level, deal with it.']
我创建dictHeaders
了一个列表列表,以便将移动值添加到每个实例的每个键中。例如,如果eachLine.startswith(old)
then 附加One
到开头,并且可能将另一个字符串附加到行尾。如果我可以用 dict 完成上述操作,我宁愿走那条路。我是 Python 新手。
我认为这是要走的路,而不是...
def changeCode(example,dictHeaders):
for old, newFront in dictHeaders:
for eachLine in example:
if eachLine.startswith(old):
return eachLine.replace(old,newFront,1)
每次我运行上面它只返回顶行,但我需要它返回整个列表example
修改..