我有以下代碼,但不幸的是它只會更改串列中的值。有什么辦法可以更改串列之外的值,以便稍后在腳本中使用?
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)
但這似乎非常耗時。預先感謝您的幫助!
PS以防萬一-除了&符號之外,我還需要進行一些檢查
uj5u.com熱心網友回復:
python 中的每個變數(例如,street_number)只是對某物的參考。在這種情況下,street_number是對字串的參考,即“100 & 102”。
當您撰寫 時allvariables = [street_number, street_name, suburb],您只是在創建一個包含已由變數初始化的元素的串列。因此,在您的串列中,位置 0 包含一個從中復制street_number并具有相同值“100 & 102”的字串,但沒有與變數 的持續鏈接street_number。
因此,如果您更新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 陳述句,該陳述句使用變數的字串名稱通過將搜索模式替換為新字串來更新變數的值&
uj5u.com熱心網友回復:
您的所有變數似乎都相互關聯,因此使用字典來存盤變數可能是個好主意。像串列一樣,您可以查看它,但與串列不同的是,您可以為其成員命名。這是一些示例代碼:
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)
uj5u.com熱心網友回復:
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
此外,將字串添加到串列意味著您所做的任何操作都不會影響原始字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/481195.html
