字符串&&列表&&字典&&元組&&集合 相互轉換詳解

1.eval() 函數   

定義:eval() 函數用來執行一個字符串表達式,並返回表達式的值。 簡單的描述就是去掉引號,只執行表達式python

本質:執行表達式的本質 若是存在運算則返回表達式的值,若是不存在運算則至關於去掉‘’ 取表達式 函數

做用:spa

1. 將字符串數據類型轉換成其它類型     把字符串類型的 列表、字典、元組,集合轉換爲表達式的類型code

a = '''[1,'b',2]'''  # 這裏純數字可套單引號,一旦包含字符就只能是三引號???
# a = '''{'a':1,'b':'eee'}'''
s = eval(a)
print(s)
print(type(s))

>>  [1, 'b', 2]
>>  <class 'list'>

   

2. 執行字符串表達式 返回表達式的值blog

x = 7
y = eval( '3 * x' )   
print(y)

>> 21

2.數據類型的相互轉換 (str list tuple dict set)

1.字符串轉換爲其餘類型ip

###字符串轉列表
s = 'hello python'
li = list(s)
print li
print type(s)
print type(li)

>>  ['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n'] 
>>  <type 'str'> 
>>  <type 'list'>

### 字符串轉爲元組
s = 'hello python'
t = tuple(s)
print t
print type(s)
print type(t)

>>  ('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')
>>  <type 'str'>
>>  <type 'tuple'>

### 字符串轉集合
s = 'hello python'
set1 = set(s)
print set1
print type(s)
print type(set1)

>> set([' ', 'e', 'h', 'l', 'o', 'n', 'p', 't', 'y'])    注意:元組 套列表 無序 問:如何把字符串轉換爲無序列表 >> <type 'str'>
>> <type 'set'>


### 字符串轉字典   eval()函數  已闡述

2.列表轉爲其它類型字符串

###列表轉化爲字符串  直接轉換類型
li=["hello",1,1+3j]
print type(li)
s=str(li)
print s
print type(s)

>>  <type 'list'>
>>  ['hello', 1, (1+3j)]
>>  <type 'str'>

### 列表轉換爲字符串  拼接字符串
l1=('a','b','c')
s = ''.join(l1)print(s)print(type(s))

### 列表轉化爲元組 tuple(l1) ### 列表轉化爲字典 li1 = ['NAME', 'AGE', 'gender'] li2 = ['redhat', 10, 'M'] d= dict(zip(li1,li2)) print d,type(d) ###列表轉集合 l1=['a',1,'c'] print(set(l1)) print(type(set(l1))) >> {1, 'c', 'a'} >> <class 'set'>

 

3.元組轉換爲其它類型class

###元組轉化成字符串  直接轉化類型
t=("hello",1,1+3j,1,"2","3","2",3)
print type(t)
s=str(t)
print s
print type(s)

>> <type 'tuple'>
>>  ('hello', 1, (1+3j), 1, '2', '3', '2', 3)
>>  <type 'str'>

###元組轉化爲列表
l1=list(t)
###元組轉化爲字典
t1 = ('NAME', 'AGE', 'gender')
t2 = ('redhat', 10, 'M')
d= dict(zip(t1,t2))
print d,type(d)

4. 字典轉換爲其它類型   容器

   1.只能將( d.keys(), d.values, for i in  dict  dict容器中裝的是keys )轉換爲其它格式數據類型

   2. 只能轉換keys 和 vaues (列表)

   3. 不能經過 dict(l1)   直接強轉類型   能夠用兩個列表,元組或集合  dict(zip(l1,l2))

 

5. 集合轉換爲其它類型

### 集合轉化爲字符串 
li={"hello",1,1+3j]}
print type(li)
s=str(li)
print s
print type(s)

### 結合轉換爲字符串  拼接字符串
t1={'a','b','c')}
s = ''.join(l1)
print(s)
print(type(s))

### 集合轉化爲元組 列表
tuple(t1)  list(t1)

### 列表轉化爲字典
t1 = {'NAME', 'AGE', 'gender'}
t2 = {'redhat', 10, 'M'}
d= dict(zip(li1,li2))
print (d,type(d))
相關文章
相關標籤/搜索