想象一下,我有一個這樣的串列:
mylist = [None, None, None, None, None, None, None, '#N/A', '#N/A', '#N/A', '#N/A', None, None, None, '#N/A', None, None, None, None, None, None, None, None, None, None, None, None, None, None]
現在我想用 None 替換所有#N/A,并且可以使用下面的代碼來做到這一點:
#Here we have to say *item and* otherwise it will return:
#AttributeError: 'NoneType' object has no attribute 'replace'
[item and item.replace("#N/A", "None") for item in mylist]
#prints
[None, None, None, None, None, None, None, 'None', 'None', 'None', 'None', None, None, None, 'None', None, None, None, None, None, None, None, None, None, None, None, None, None, None]
但是,當串列中包含整數時,我不能再執行這個操作了,不知道如何優雅地解決這個問題?
mylist = ['xxx', None, 'x', 'x', None, 'Pv', 0, 0, 0, 0, 0, 0, 0, 1, '00000001', '#N/A', 'na', 'na', 'na', 'na', 'na', 'na', 'Suc', 171.1, 'na', 'na',
6, None, 'H(1970)']
[item and item.replace("#N/A", "None") for item in mylist]
#prints
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<stdin>", line 4, in <listcomp>
**AttributeError: 'int' object has no attribute 'replace'**
對于任何獎勵積分,我也無法使用替換功能將字串轉換為無:
[item and item.replace("#N/A", None) for item in mylist]
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
TypeError: replace() argument 2 must be str, not None
uj5u.com熱心網友回復:
你可以試試這個:
newlist = [None if item == '#N/A' else item for item in mylist]
無論串列中包含的資料型別如何,這都將起作用。
鑒于:
mylist = [
"xxx",
None,
"x",
"x",
None,
"Pv",
0,
0,
0,
0,
0,
0,
0,
1,
"00000001",
"#N/A",
"na",
"na",
"na",
"na",
"na",
"na",
"Suc",
171.1,
"na",
"na",
6,
None,
"H(1970)",
]
上面的代碼產生:
[
"xxx",
None,
"x",
"x",
None,
"Pv",
0,
0,
0,
0,
0,
0,
0,
1,
"00000001",
None,
"na",
"na",
"na",
"na",
"na",
"na",
"Suc",
171.1,
"na",
"na",
6,
None,
"H(1970)",
]
(如果您希望所有這些na值都是,#N/A那么它們當然會None以結果形式結束。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523802.html
上一篇:從字串中反轉奇數長度的單詞
