在 Python 中,有时候我们需要替换一个列表中的元素,但又不想使用 list.replace()
方法,因为该方法只会替换列表中的第一个匹配元素。那么,有没有办法可以替换列表中的所有匹配元素呢?
2、解决方案
一种解决方案是使用 re.sub()
方法。re.sub()
方法可以接受三个参数:第一个参数是要替换的正则表达式,第二个参数是要替换的字符串,第三个参数是要被替换的字符串。
例如,以下代码可以将列表 list1
中的所有元素替换为列表 list2
中的相应元素:
list1 = ["372911000002001", "372809000001400", "372809000001500"]
list2 = ["372911000003100", "372909000001400", "372909000001500"]
for ii, jj in zip(list1, list2):
newname = re.sub(ii, jj, ARN) # re.sub returns ARN if no substitution done
if newname != ARN:
break
这段代码首先使用 zip()
函数将两个列表打包成一个元组列表,然后使用 re.sub()
方法将每个元组中的第一个元素替换为第二个元素。最后,使用 break
语句跳出循环。
这种方法的优点是,它可以替换列表中的所有匹配元素,而且不会改变原有的列表。
代码例子
import os
import re
import sys
import traceback
import collections
import shutil
movdir = r"C:\Scans"
basedir = r"C:\Links"
subfolder = "\Private Drain Connections"
l = ['372911000002001', '372809000001400', '372809000001500', '372809000001700', '37292200000800']
l2 = ['372911000003100', '372909000001400', '372909000001500', '372909000001700', '372922000000800']
try:
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
for filename in files:
# find the name location and name of files
path = os.path.join(root, filename)
# file name and extension
ARN, extension = os.path.splitext(filename)
oldname = str(ARN)
# Location of the corresponding folder in the new directory
link = os.path.join(basedir, ARN)
if not os.path.exists(link):
for ii, jj in zip(l, l2):
newname = re.sub(ii, jj, ARN)
newname = str(newname)
print(path)
newpath = os.path.join(root, oldname) + extension
print("new name", newpath)
os.rename(path, newpath)
print("Renaming")
newpath2 = basedir + "\\" + newname + subfolder
shutil.copy(newpath, newpath2)
print("Copied")
if newname != ARN:
break
else:
continue
except:
print("Error occurred")
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n " + \
str(sys.exc_type) + ": " + str(sys.exc_value) + "\n"
msgs = "GP ERRORS:\n" + arcpy.GetMessages(2) + "\n"
print(pymsg)
print(msgs)
这段代码将遍历 movdir
目录下的所有文件,并使用 re.sub()
方法将每个文件名的第一个元素替换为第二个元素。然后,将修改后的文件名保存到 newpath
变量中,并将文件复制到 newpath2
目录中。