python 列表中的数字转字符串_python 将列表中的字符串转为数字
python 將列表中的字符串轉為數字
轉自:https://www.jb51.net/article/86561.htm
本文實例講述了Python中列表元素轉為數字的方法。分享給大家供大家參考,具體如下:
有一個數字字符的列表:
1
numbers
=
[
'1'
,
'5'
,
'10'
,
'8'
]
想要把每個元素轉換為數字:
1
numbers
=
[
1
,
5
,
10
,
8
]
用一個循環來解決:
1
2
3
4
new_numbers
=
[];
for
n
in
numbers:
new_numbers.append(
int
(n));
numbers
=
new_numbers;
有沒有更簡單的語句可以做到呢?
1.
1
numbers
=
[
int
(x)
for
x
in
numbers ]
2. Python2.x,可以使用map函數
1
numbers
=
map
(
int
, numbers)
如果是3.x,map返回的是map對象,當然也可以轉換為List:
1
numbers
=
list
(
map
(
int
, numbers))
3.還有一種比較復雜點:
for i, v in enumerate(numbers): numbers[i] = int(v)
python字符數字之間的轉換:轉自https://www.cnblogs.com/wuxiangli/p/6046800.html
int(x [,base ]) ? ? ? ? 將x轉換為一個整數
long(x [,base ]) ? ? ? ?將x轉換為一個長整數
float(x ) ? ? ? ? ? ? ? 將x轉換到一個浮點數
complex(real [,imag ]) ?創建一個復數
str(x ) ? ? ? ? ? ? ? ? 將對象 x 轉換為字符串
repr(x ) ? ? ? ? ? ? ? ?將對象 x 轉換為表達式字符串
eval(str ) ? ? ? ? ? ? ?用來計算在字符串中的有效Python表達式,并返回一個對象
tuple(s ) ? ? ? ? ? ? ? 將序列 s 轉換為一個元組
list(s ) ? ? ? ? ? ? ? ?將序列 s 轉換為一個列表
chr(x ) ? ? ? ? ? ? ? ? 將一個整數轉換為一個字符
unichr(x ) ? ? ? ? ? ? ?將一個整數轉換為Unicode字符
ord(x ) ? ? ? ? ? ? ? ? 將一個字符轉換為它的整數值
hex(x ) ? ? ? ? ? ? ? ? 將一個整數轉換為一個十六進制字符串
oct(x ) ? ? ? ? ? ? ? ? 將一個整數轉換為一個八進制字符串
chr(65)='A'
ord('A')=65
int('2')=2;
str(2)='2'
總結
以上是生活随笔為你收集整理的python 列表中的数字转字符串_python 将列表中的字符串转为数字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python apply_async数据
- 下一篇: python时间重叠_python-检测