Python 将列表中的数字乘以字符串
我一直在想是否有办法做到这一点Python 将列表中的数字乘以字符串,python,list,Python,List,我一直在想是否有办法做到这一点 import re myList = ["a6C"] >>> ["a12C"] updatedLst=[] for indx,item in enumerate(myList): val=(re.findall('\d+', item)) myList[indx]=val print(myList) 我可以这样做的一种方法是通过硬编码如下的值 如果项目中的“6”: 我想用另一种方式做。我明白没有理由使用这样的混合列表或糟
import re
myList = ["a6C"] >>> ["a12C"]
updatedLst=[]
for indx,item in enumerate(myList):
val=(re.findall('\d+', item))
myList[indx]=val
print(myList)
我可以这样做的一种方法是通过硬编码如下的值
如果项目中的“6”:
我想用另一种方式做。我明白没有理由使用这样的混合列表或糟糕的设计。。。我只是想找出解决这个问题的“方法”/逻辑。感谢您的想法和时间。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
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
嗯,它只适用于一个位数,但是
re.sub
是一种方法
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