python 將列表中的字串轉為數字

來源:互聯網
上載者:User

標籤:簡單的   沒有   none   int   http   lis   方法   函數   簡單   

本文執行個體講述了Python中列表元素轉為數位方法。分享給大家供大家參考,具體如下:

有一個數字字元的列表:

numbers = [‘1‘, ‘5‘, ‘10‘, ‘8‘]

想要把每個元素轉換為數字:

numbers = [1, 5, 10, 8]

用一個迴圈來解決:

new_numbers = [];for n in numbers:  new_numbers.append(int(n));numbers = new_numbers;

有沒有更簡單的語句可以做到呢?

1.

numbers = [ int(x) for x in numbers ]

2. Python2.x,可以使用map函數

numbers = map(int, numbers)

如果是3.x,map返回的是map對象,當然也可以轉換為List:

numbers = list(map(int, numbers))

3.還有一種比較複雜點:

for i, v in enumerate(numbers): numbers[i] = int(v)


轉:https://www.jb51.net/article/86561.htm

python 將列表中的字串轉為數字

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.