需要检查我所有的变量是否有符号,我把变量放在一个列表中,并使用for循环进行检查,但Python只更改列表中的值



我得到了以下代码,但不幸的是,它只更改了列表中的值。有没有什么方法可以更改列表之外的值,以便稍后在脚本中使用它?

street_number = "100 & 102"
street_name = "Fake Street"
suburb = "Faketown"
allvariables = [street_number, street_name, suburb]
ampersand = "&"
ampersand_escape = "&"
for i, item in enumerate(allvariables):
if isinstance(item, str):
if ampersand in item:
allvariables[i] = item.replace(ampersand,ampersand_escape)
print(allvariables) # -> ['100 & 102', 'Fake Street', 'Faketown']
print(street_number) # -> 100 & 102

我能想象的唯一替代方案是单独检查每个变量,但我有很多变量需要检查,所以这需要很长时间:

if ampersand in street_number:
street_number.replace(ampersand,ampersand_escape)
if ampersand in street_name:
street_name.replace(ampersand,ampersand_escape)
if ampersand in suburb:
suburb.replace(ampersand,ampersand_escape)

但这似乎非常耗时。提前感谢您的帮助!

p。S.以防万一-除了安培数之外,我还需要再做一些检查

python中的每个变量(例如street_number)都只是对某个事物的引用。在这种情况下,street_number是对字符串的引用,即"1";100&102";。

当您编写allvariables = [street_number, street_name, suburb]时,您只需创建一个包含已由变量初始化的元素的列表。因此,在您的列表中,位置0包含一个从street_number复制的字符串,并且具有相同的值"0";100&102〃;,但是不存在到变量CCD_ 5的正在进行的链接。

因此,如果将allvariables[0]更新为"100&102’,这将对变量street_number所引用的值没有影响。

得到我想你想要的结果的一种方法是:

street_number = "100 & 102"
street_name = "Fake Street"
suburb = "Faketown"
allvariableNames = ['street_number', 'street_name', 'suburb']
ampersand = "&"
ampersand_escape = "&"
ampIndices = [i for i, item in enumerate(allvariableNames) if isinstance(eval(item), str) and ampersand in eval(item)]
for i in ampIndices:
exec(f'{allvariableNames[i]} = {allvariableNames[i]}.replace(ampersand, ampersand_escape)')
print(', '.join(f"'{eval(item)}'" for item in allvariableNames)) # -> ['100 & 102', 'Fake Street', 'Faketown']
print(street_number)

输出:

'100 & 102', 'Fake Street', 'Faketown'
100 & 102

说明:

  • 不要使用您心目中的变量初始化列表,而是使用这些变量的名称作为字符串初始化列表
  • 为包含搜索模式的变量(使用eval()函数获得)的值在变量名称列表中构建索引列表
  • 使用exec()执行python语句,该语句使用变量的字符串名称,通过用新字符串&amp替换搜索模式来更新变量的值

看起来所有的变量都是相互关联的,所以使用字典来存储变量可能是个好主意。就像列表一样,你可以查看它,但与列表不同的是,你可以给它的成员起名字。下面是一些示例代码:

address = {
"street_number": "100 & 102",
"street_name": "Fake Street",
"suburb": "Faketown",
}
ampersand = "&"
ampersand_escape = "&"
for (item, value) in address.items():
if isinstance(value, str):
if ampersand in value:
address[item] = value.replace(ampersand,ampersand_escape)
print(address)
Python中的字符串是不可变的,这意味着一旦创建,就不能更改它们。只能创建一个新字符串。因此,您要做的是将新创建的字符串存储回同一个变量中。例如
s = "hello"
s.upper() #does not change s.. only creates a new string and discards it
s = s.upper() # creates the new string but then overrides the value of s

此外,将字符串添加到列表中意味着您所做的任何操作都不会影响原始字符串。

最新更新