我有一個字串串列,例如:
df = [['cutting_board', 'knife', 'cucumber', 'plate'],
['bread', 'plate', 'knife', 'cutting_board'],
['cutting_board', 'knife', 'orange', 'plate'],
[ 'plate', 'garlic', 'knife']]
我有一些類別,例如:
Kitchen_staffs =['knife', 'cutting_board', 'plate', ]
food = ['cucumber', 'bread', 'orange','garlic']
如何使用 Python 將串列中的字串替換為類別?我希望我的輸出看起來像這樣:
df = [['Kitchen_staffs', 'Kitchen_staffs', 'food', 'Kitchen_staffs'],
['food', 'Kitchen_staffs', 'Kitchen_staffs', 'Kitchen_staffs']]
uj5u.com熱心網友回復:
這是您案例的作業代碼
for arr in df:
for index, name in enumerate(arr):
if name in Kitchen_staffs:
arr[index] = 'Kitchen_staffs'
elif name in food:
arr[index] = 'food'
但就個人而言,我建議您將所有“替換”項放入字典中,這樣可以更輕松地擴展代碼(即不必elif每次都添加更多)
replacements = {
'Kitchen_staffs': ['knife', 'cutting_board', 'plate', ],
'food': ['cucumber', 'bread', 'orange','garlic']
}
for arr in df:
for index, name in enumerate(arr):
for replace_name, items in replacements.items():
if name in items:
arr[index] = replace_name
uj5u.com熱心網友回復:
也許是這樣的:
new_list = [["Kichen" if word in Kitchen_staffs else "food" for word in line if word in Kitchen_staffs or word in food ] for line in df ]
uj5u.com熱心網友回復:
您可以使用串列理解。
df = [['cutting_board', 'knife', 'cucumber', 'plate'],
['bread', 'plate', 'knife', 'cutting_board'],
['cutting_board', 'knife', 'orange', 'plate'],
['plate', 'garlic', 'knife']]
Kitchen_staffs =['knife', 'cutting_board', 'plate', ]
food = ['cucumber', 'bread', 'orange','garlic']
arr1 = [['Kitchen_staffs' if name in Kitchen_staffs else 'food' for idx, name in enumerate(arr)] for arr in df ]
print(arr1)
輸出:
[['Kitchen_staffs', 'Kitchen_staffs', 'food', 'Kitchen_staffs'], ['food', 'Kitchen_staffs', 'Kitchen_staffs', 'Kitchen_staffs'], ['Kitchen_staffs', 'Kitchen_staffs', 'food', 'Kitchen_staffs'], ['Kitchen_staffs', 'food', 'Kitchen_staffs']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/514023.html
