2 回答

TA貢獻2041條經驗 獲得超4個贊
由于您是 Python 的新手,我不想讓答案復雜化。
為了讓您開始了解一些基礎知識,這里有一種查看解決方案的方法。
您可以使用 if 語句來檢查您想要的每個值。然后用新值替換該值。
#you want to iterate through list1 and for each value in list1,
#you want to check if it meets your criteria
#since you need the index and value, use enumerate
for i,val in enumerate(list1):
#if value is 'steel' you want to replace with 'MCSTEL'
if list1[i].lower() == 'steel':
list1[i] = 'MCSTEL'
print (list1)
如果要替換的項目不止一項,則可以有多個 if 語句。
#you want to iterate through list1 and for each value in list1,
#you want to check if it meets your criteria
#since you need the index and value, use enumerate
for i,val in enumerate(list1):
#if value is 'Steel' you want to replace with 'MCSTEL'
if val.lower() == 'steel':
list1[i] = 'MCSTEL'
#if value is 'ReinfSteel' you want to replace with 'REINFO'
if val.lower() == 'reinfsteel':
list1[i] = 'REINFO'
如果您熟悉字典,則可以使用字典來遍歷列表。
首先你需要定義字典。然后遍歷列表以將與字典中的鍵匹配的每個元素替換為字典中的值。
#define your dictionary with key value pairs
#key is the value you want to search in list1
#value is the new value you want to store
d = {'steel':'MCSTEL','reinfsteel':'REINFO'}
#you want to iterate through list1 and for each value in list1,
#you want to check if it meets your criteria
#since you need the index and value, use enumerate
for i,val in enumerate(list1):
#check against the keys in the dictionary
if val.lower() in d.keys():
list1[i] = d[val.lower()]
如果你了解 python 中的列表理解,那么你可以將上面的循環寫在一個語句中:
list2 = [d[x.lower()] if x.lower() in d.keys() else x for x in list1]
任何一個代碼都將替換:
['Steel', 'ReinfSteel', 'Concrete', 'Wood', 'Aluminium']
到
['MCSTEL', 'REINFO', 'Concrete', 'Wood', 'Aluminium']

TA貢獻1835條經驗 獲得超7個贊
dict
您可以為要交換的內容創建一個鍵值對,然后使用列表理解來創建新列表。下面是一個只有鋼的例子。
d = {"Steel": "MCSTEL"} new_list = [d[i] if i in d else i for i in List1]
"Concrete": "CONCR"
如果您想包含其他內容,例如“Concrete”和“CONCR”,您可以在字典中包含鍵值對d
。
添加回答
舉報