我有兩個清單:
main = [1,2,3,4,5,6,7,8,20]
replace_items = [6,8,20]
我希望這個替換專案替換為 replace_items*10 即 [60, 80,200]
所以結果主串列將是:
main = [1,2,3,4,5,60,7,80,200]
我的審判:
我收到一個錯誤:
for t in replace_items:
for o in main:
main = o.replace(t, -(t-100000), regex=True)
print(main)
以下是我得到的錯誤:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-592-d3f3f6915a3f> in <module>
14 main = o.replace(t, -(t-100000), regex=True)
---> 15 print(main)
TypeError: replace() takes no keyword arguments
uj5u.com熱心網友回復:
您可以使用串列理解:
main = [x * 10 if x in replace_items else x for x in main]
輸出:
print(main)
[1, 2, 3, 4, 5, 60, 7, 80, 200]
uj5u.com熱心網友回復:
由于您最初有一個pandas標簽,因此您可能對矢量解決方案感興趣。
這里使用 numpy
import numpy as np
main = np.array([1,2,3,4,5,6,7,8,20])
replace_items = np.array([6,8,20]) # a list would work too
main[np.in1d(main, replace_items)] *= 10
輸出:
>>> main
array([ 1, 2, 3, 4, 5, 60, 7, 80, 200])
uj5u.com熱心網友回復:
你可以這樣做
for (index,mainItems) in enumerate(main) :
if mainItems in replace_items :
main[index] *= 10
通過使用enumerate(main)您可以訪問索引和專案
uj5u.com熱心網友回復:
使用pandas你可以做
import pandas as pd
main = pd.Series([1,2,3,4,5,6,7,8,20])
replace_items = [6,8,20]
main[main.isin(replace_items)] *= 10
print(main.values)
輸出
[ 1 2 3 4 5 60 7 80 200]
說明:使用pandas.Series.isin發現它們的一個元素replace_items,something *= 10簡潔的方式來寫something = something * 10
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/357680.html
標籤:Python 蟒蛇-3.x 列表 python-2.7
上一篇:子行程解壓縮源檔案洗掉?
