我有一個串列 list1=['a','b','c','a','c','d','a','b',10,20] ,該串列可能包含更多帶有 'a'、'b'、'c'、'd' 和 'e' 在隨機位置的元素。我想用 10 替換“a”,用 0 替換“b”,用 20 替換“c”,用 100 替換“d”,用 -10 替換“e”。所以基本上輸出串列應該是(對于list1):[10,0,20,10,20,100,10,0,10,20]
我有一個串列 list1=['a','b','c','a','c','d','a','b',10,20] ,該串列可能包含更多在隨機索引位置具有 'a'、'b'、'c'、'd' 和 'e' 的元素。我想在串列中將 'a' 替換為 10,將 'b' 替換為 0,將 'c' 替換為 20,將 'd' 替換為 100,將 'e' 替換為 -10。所以基本上輸出串列應該是(對于list1):[10,0,20,10,20,100,10,0,10,20] 注意:我不想替換數字元素
uj5u.com熱心網友回復:
您要做的是一個值到另一個值的基本映射。這通常使用定義映射的字典來完成,然后遍歷您要映射的所有值并應用映射。
以下是可以為您帶來預期結果的方法。一種是使用串列推導,第二種方法是使用map()內置函式。
list1 = ['a', 'b', 'c', 'a', 'c', 'd', 'a', 'b']
mapping = {
"a": 10,
"b": 0,
"c": 20,
"d": 100,
"e": -10
}
# option 1 using a list comprehension
result = [mapping[item] for item in list1]
print(result)
# another option using the built-in map()
alternative = list(map(lambda item: mapping[item], list1))
print(alternative)
預期輸出:
[10, 0, 20, 10, 20, 100, 10, 0]
[10, 0, 20, 10, 20, 100, 10, 0]
編輯
根據評論中的要求,這里有一個版本,它只映射定義了映射的值。如果未定義映射,則回傳原始值。我再次實作了這兩種變體。
# I have added some values which do not have a mapping defined
list1 = ['a', 'b', 'c', 'a', 'c', 'd', 'a', 'b', 'z', 4, 12, 213]
mapping = {
"a": 10,
"b": 0,
"c": 20,
"d": 100,
"e": -10
}
def map_value(value):
"""
Maps value to a defined mapped value or if no mapping is defined returns the original value
:param value: value to be mapped
:return:
"""
if value in mapping:
return mapping[value]
return value
# option 1 using a list comprehension
result = [map_value(item) for item in list1]
print(result)
# another option using the built-in map()
alternative = list(map(map_value, list1))
print(alternative)
預期產出
[10, 0, 20, 10, 20, 100, 10, 0, 'z', 4, 12, 213]
[10, 0, 20, 10, 20, 100, 10, 0, 'z', 4, 12, 213]
如您所見'z',4, 12,213不受影響,因為它們沒有定義映射。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450105.html
標籤:python-3.x 列表
上一篇:回傳游戲和結果的摘要
