简体   繁体   English

替换列表中的项目,python

[英]Replace items in list, python

I have a list of strings like this: 我有一个像这样的字符串列表:

Item_has_was_updated_May_2010
Item_updated_Apr_2011
Item_got_updated_Sept_2011

I want to iterate through the list of string and update the last 2 parts of the string. 我想迭代字符串列表并更新字符串的最后两部分。 The month and the year. 一个月和一年。 The rest of the string I want to remain the same. 字符串的其余部分我想保持不变。 The month and year will be taken from variables I have set earlier in my script, so let's call the month x and the year y. 月份和年份将取自我之前在脚本中设置的变量,因此我们称之为月份x和年份y。

My approach is to: 我的方法是:

  1. Iterate through the list of strings 遍历字符串列表
  2. Split each string by "_" 用“_”分割每个字符串
  3. Replace the last 2 items 替换最后2项
  4. Join the items back together with the replaced items 将物品与更换的物品一起加入

The month and year will be taken from variables I have set earlier in my script, so let's call the month x and the year y. 月份和年份将取自我之前在脚本中设置的变量,因此我们称之为月份x和年份y。

If anyone can suggest a an approach, it is appreciated. 如果有人可以建议一种方法,我们将不胜感激。

You can do it without regular expressions by using str.rsplit : 您可以使用str.rsplit在没有正则表达式的情况下执行此str.rsplit

yourlist = [s.rsplit('_', 2)[0] + '_' + x + '_' + y for s in yourlist]

See it working online: ideone 看到它在线工作: ideone


If you want to use formatting instead of string concatenation, try this: 如果要使用格式而不是字符串连接,请尝试以下操作:

yourlist = ['{}_{}_{}'.format(s.rsplit('_', 2)[0], x, y) for s in yourlist]

See it working online: ideone 看到它在线工作: ideone

I don't think you really need 're'. 我不认为你真的需要'重新'。
You could use something like this: 你可以使用这样的东西:

m="dec"
y=2012
l=["Item_has_was_updated_May_2010",
    "Item_updated_Apr_2011",
    "Item_got_updated_Sept_2011"]
r=[]
for s in l:
    t=s.split("_")
    r.append("_".join(t[:-2])+"_%s_%s"%(m,y))
lst = [
   'Item_has_was_updated_May_2010',
   'Item_updated_Apr_2011',
   'Item_got_updated_Sept_2011',
]
month='Sep';year='2012'
for s in lst:
        list=s.split('_')
        list[-2:]=(month,year)
        r=''
        for a in list:
                r=r+"%s_"%a
        r=r[:-1]
        print r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM