简体   繁体   English

需要检查我的所有变量是否有 &

[英]Need to check all my variables for an ampersand, I put variables in a list and check using a for loop, but Python only changes value inside list

I've got the following code, but unfortunately it only changes the value inside the list.我有以下代码,但不幸的是它只会更改列表中的值。 Is there any way I can change the value outside the list, so it can be used later in the script?有什么办法可以更改列表之外的值,以便稍后在脚本中使用?

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

The only alternative I can imagine is checking each variable individually, but I've got a LOT of variables that need to be checked so it would take forever:我能想象的唯一选择是单独检查每个变量,但是我有很多变量需要检查,所以这需要很长时间:

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)

But that seems extremely time consuming.但这似乎非常耗时。 Thank you in advance for your help!预先感谢您的帮助!

PS just in case - I need to do a few more checks besides the ampersands PS以防万一-除了&符号之外,我还需要进行一些检查

Each variable in python (for instance, street_number ) is just a reference to something. python 中的每个变量(例如street_number )只是对某些东西的引用。 In this case, street_number is a reference to a string, namely "100 & 102".在这种情况下, street_number是对字符串的引用,即“100 & 102”。

When you write allvariables = [street_number, street_name, suburb] , you are simply creating a list with elements that have been initialized by the variables.当您编写allvariables = [street_number, street_name, suburb]时,您只是在创建一个包含已由变量初始化的元素的列表。 So in your list, position 0 contains a string which was copied from street_number and has the same value "100 & 102", but there is no ongoing linkage to the variable street_number .因此,在您的列表中,位置 0 包含一个从street_number复制的字符串,并且具有相同的值“100 & 102”,但没有与变量street_number的持续链接。

So if you update allvariables[0] to be '100 & 102', this will have no effect on the value referenced by the variable street_number .因此,如果您将allvariables[0]更新为 '100 & 102',这对变量street_number引用的值没有影响。

One way to get the result I think you want would be this:获得我认为您想要的结果的一种方法是:

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)

Output:输出:

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

Explanation:解释:

  • instead of initializing a list using the variables you have in mind, initialize a list with the names of these variables as strings不要使用您想到的变量来初始化列表,而是使用这些变量的名称作为字符串初始化列表
  • build a list of the indices into the variable name list for the value of the variable (obtained using the eval() function) contains the search pattern将索引列表构建到变量值的变量名称列表中(使用eval()函数获得)包含搜索模式
  • use exec() to execute a python statement that uses the string name of the variable to update the variable's value by replacing the search pattern with the new string &amp使用exec()执行 python 语句,该语句使用变量的字符串名称通过用新字符串&amp替换搜索模式来更新变量的值

It seems like all your variables are related to each other, so using a dictionary to store the variables might be a good idea.您的所有变量似乎都相互关联,因此使用字典来存储变量可能是个好主意。 Like a list, you can look over it, but unlike a list, you can give its members names.像列表一样,您可以查看它,但与列表不同的是,您可以为其成员命名。 Here's some example code:这是一些示例代码:

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)

Strings in Python are immutable which means that once created they cannot be changed. Python 中的字符串是不可变的,这意味着一旦创建它们就无法更改。 Only a new string can be created.只能创建一个新字符串。 So what you want to do is to store the newly created string back in the same variable.因此,您要做的是将新创建的字符串存储回同一个变量中。 for example例如

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

Also, adding strings to the list means any manipulation you do won't affect the original string.此外,将字符串添加到列表意味着您所做的任何操作都不会影响原始字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM