[英]How to change the nth character of every string in a list in Python
假設我有以下字符串列表:
list = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03']
我想將每個字符串的第 11 個字符(即第二個“.”)更改為“-”。 我試過了:
list = [n[:10] + '-' + n[11:] for n in list]
然而,這給了我錯誤:
TypeError: 'float' object is not subscriptable
問題是您的列表中某處有一個浮點數。 您可以使用 for 循環使用enumerate
和str
來解決它:
lst = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03']
for index, item in enumerate(lst):
item = str(item)
lst[index] = item[0:10] + "-" + item[11:]
或者,作為列表理解:
new_lst = [item[0:10] + "-" + item[11:]
for x in lst
for item in [str(x)]]
此外,避免調用您的變量,如內置對象( list
、 dict
等)。
我剛剛在 Jupyter localhost 上嘗試過,(它正在工作):
>>> a = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03']
>>> a = [n[:10] + '-' + n[11:] for n in a]
>>> a
['ABC.010120-01', 'ABC.010220-02', 'ABC.010220-03']
請注意, list
,如str
, set
和其他一些是為 python3 保留的字。
例如,您所做的就像更改int
的基礎。
問題是列表中有 nan float 值。 我發現按照此處鏈接的此解決方案可以從我的列表中刪除 nan,如下所示:
lst = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03', nan]
lst = [x for x in lst if x == x]
預先執行該命令允許此行到 function 沒有錯誤:
lst = [n[:10] + '-' + n[11:] for n in last]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.