[英]Convert type 'str' to numerator/ denominator
我在將類型“str”轉換為數字時遇到了一些麻煩。 我使用一個單獨的文本文件,其中包含以下數字1, 2, 3, 4, 5, 6
然后將這些數字導入 python 並將它們保存為列表。 但是,通過這樣做,我得到了一個字符串列表,如下所示: ['1', '2', '3', '4', '5', '6']
。 我想轉換這個字符串列表,以便該列表代表數字,即輸出應該是[1, 2, 3, 4, 5, 6]
。
我的代碼是:
def imported_numbers(filename):
with open(filename, 'r') as f:
contents = f.read().splitlines()
print(contents)
imported_numbers('sample.txt')
是否有特定的命令來執行此操作?
IMO 說起來更像是 Pythonic
str_list = ['1', '2', '3']
new_list = [int(n) for n in str_list]
如果您不確定所有字符串都是有效數字,則需要添加適當的錯誤處理。
您可以使用map
:
l = ['1', '2', '3', '4', '5', '6']
new_l = list(map(int, l)) # or just map(int, l) in Python 2
將返回
[1, 2, 3, 4, 5, 6]
如果存在無法轉換為數字的字符串,這可能會引發錯誤:
l = ['1', '2', '3', '4', '5', 'lkj']
list(map(int, l))
ValueError:int() 的無效文字,基數為 10:'lkj'
因此,請確保您的輸入有效和/或將其包裝到try/except
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.