如何将字符附加到列表中项目的特定部分 - Python
How to append character to specific part of item in list - Python
我有以下列表Novar
:
["'population_3000|road_class_3_3000'", "'population_3000|road_class_3_3000|trafBuf25'", "'population_3000|road_class_3_3000|trafBuf25|population_1000'"]
如何将字符(例如 $
)附加到 列表中项目的特定部分,例如附加到 road_class_3_3000
,所以升级后的列表变为:
["'population_3000|road_class_3_3000$'", "'population_3000|road_class_3_3000$|trafBuf25'", "'population_3000|road_class_3_3000$|trafBuf25|population_1000'"]
Stack Overflow 上的大多数类似问题似乎都集中在操纵项目本身,而不是项目的一部分,例如here and here.
因此,应用以下代码:
if (item == "road_class_3_3000"):
item.append("$")
没有用,因为 road_class_3_3000
是项目 "'population_3000|road_class_3_3000'"
、"'population_3000|road_class_3_3000|trafBuf25'"
和 "'population_3000|road_class_3_3000|trafBuf25|population_1000'"
的一部分
您可以按照以下方式利用 re
模块(标准库的一部分)完成此任务
import re
novar = ["'population_3000|road_class_3_3000'", "'population_3000|road_class_3_3000|trafBuf25'", "'population_3000|road_class_3_3000|trafBuf25|population_1000'"]
novar2 = [re.sub(r'(?<=road_class_3_3000)', '$', i) for i in novar]
print(novar2)
输出
["'population_3000|road_class_3_3000$'", "'population_3000|road_class_3_3000$|trafBuf25'", "'population_3000|road_class_3_3000$|trafBuf25|population_1000'"]
我使用的功能称为 positive lookbehind,这是一种 zero-length 断言。我在 zer-length 的 road_class_3_3000
之后寻找位置,然后使用 $
字符替换它。
我有以下列表Novar
:
["'population_3000|road_class_3_3000'", "'population_3000|road_class_3_3000|trafBuf25'", "'population_3000|road_class_3_3000|trafBuf25|population_1000'"]
如何将字符(例如 $
)附加到 列表中项目的特定部分,例如附加到 road_class_3_3000
,所以升级后的列表变为:
["'population_3000|road_class_3_3000$'", "'population_3000|road_class_3_3000$|trafBuf25'", "'population_3000|road_class_3_3000$|trafBuf25|population_1000'"]
Stack Overflow 上的大多数类似问题似乎都集中在操纵项目本身,而不是项目的一部分,例如here and here.
因此,应用以下代码:
if (item == "road_class_3_3000"):
item.append("$")
没有用,因为 road_class_3_3000
是项目 "'population_3000|road_class_3_3000'"
、"'population_3000|road_class_3_3000|trafBuf25'"
和 "'population_3000|road_class_3_3000|trafBuf25|population_1000'"
您可以按照以下方式利用 re
模块(标准库的一部分)完成此任务
import re
novar = ["'population_3000|road_class_3_3000'", "'population_3000|road_class_3_3000|trafBuf25'", "'population_3000|road_class_3_3000|trafBuf25|population_1000'"]
novar2 = [re.sub(r'(?<=road_class_3_3000)', '$', i) for i in novar]
print(novar2)
输出
["'population_3000|road_class_3_3000$'", "'population_3000|road_class_3_3000$|trafBuf25'", "'population_3000|road_class_3_3000$|trafBuf25|population_1000'"]
我使用的功能称为 positive lookbehind,这是一种 zero-length 断言。我在 zer-length 的 road_class_3_3000
之后寻找位置,然后使用 $
字符替换它。