![](/img/trans.png)
[英]How to remove all string elements from a list of integers, with strings next to integers [Python]
[英]Change specific elements of a list from string to integers in python
如果我有一個列表如
c=['my', 'age', 'is', '5\\n','The', 'temperature', 'today' 'is' ,'87\\n']
我如何專門將列表的數字轉換為整數,留下其余的字符串,並擺脫\\ n?
預期產量:
`c=['my', 'age', 'is', 5,'The', 'temperature', 'today' 'is' ,87]`
我嘗試使用'map()'和'isdigit()'函數,但它沒有用。
謝謝。
您可以編寫一個嘗試轉換為int
的函數,如果失敗則返回原始函數,例如:
def conv(x):
try:
x = int(x)
except ValueError:
pass
return x
>>> c = ['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']
>>> list(map(conv, c))
['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87]
>>> [conv(x) for x in c]
['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87]
注意:由空格分隔的2個字符串由python自動連接,例如'today' 'is'
相當於'todayis'
如果您不知道文本中整數的格式,或者只有太多的變體,那么一種方法就是在所有內容上嘗試int()
並查看成功或失敗的內容:
original = ['my', 'age', 'is', '5\n', 'The', 'temperature', 'today', 'is', '87\n']
revised = []
for token in original:
try:
revised.append(int(token))
except ValueError:
revised.append(token)
print(revised)
通常使用try
和except
作為算法的一部分,不僅僅是你的錯誤處理,這是一種不好的做法,因為它們效率不高。 但是,在這種情況下,很難預測int()
或float()
可以成功處理的所有可能輸入,因此try
方法是合理的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.