【问题标题】:multiply a digit inside list as string将列表中的数字乘以字符串
【发布时间】:2019-03-10 03:36:04
【问题描述】:

我一直在想是否有办法做到这一点

import re
myList = ["a6C"] >>> ["a12C"]

updatedLst=[]


for indx,item in enumerate(myList):
    val=(re.findall('\d+', item))
    myList[indx]=val

print(myList)

我可以做到这一点的一种方法是硬编码这样的值 如果项目中有“6”:

我想以不同的方式来做。我知道没有理由使用这种混合列表或糟糕的设计......我只是想找出解决这个问题的“方式”/逻辑。感谢您的想法和时间。

【问题讨论】:

标签: python list


【解决方案1】:

IIUC,使用:

import re
myList = ["a6C"]
for indx, item in enumerate(myList):
    myList[indx] = ''.join([str(int(i)*2) if i.isdigit() else i for i in item])
print(myList)

或者:

import re
myList = ["a6C"]
for indx, item in enumerate(myList):
    myList[indx] = re.sub('\d+',str(int(re.sub('\D+','',item))*2),item)
print(myList)

【讨论】:

    【解决方案2】:

    我想出了一个效率不高的版本。

    import re
    strng="ro5e"
    
    #the following variable finds numeric value and saves in variable num
    num=re.findall('\d+',strng)
    
    #for item in strng: will not find numeric value because everything will be String there
    #Hence the following approach,iterate num
    for i in num:
         v=int(i)*2 #using int to convert String to int so that I can multiply
         print(strng.replace(i,str(v)))#again converting to str so that I can replace
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多