python 内置函数等的相互转换示例

1、list
#判断列表是否为空
b=[]
if len(b):
    print('b has elements')
else:
    print('b has no element')

out:
b has no element

 

#判断列表是否含有某个元素,含有某个元素的话,请输出相应的索引
b=[1,3,4,2,12,34,6,7] 
if 2 in b:
    print('has')
    index = b.index(2)
    print('index is %s'% index)
else:
    print('not have')

out:
has
index is 3

  

 

#list的切片范围,list索引从0开始,切片取值的尾数的前一位,即3-1=2
b=[1, 3, 4, 2, 12, 34, 6, 7]
b[1:3]

out:
[3, 4]

  

 

#切片步长,最后一位表示步长,这里即为2,而不是中间的数
b=[1, 3, 4, 2, 12, 34, 6, 7]
b[1::2]

out:
[3, 2, 34, 7]

  

#对list进行增
b=[1, 3, 4, 2, 12, 34, 6, 7]
b.append(222)
print(b)
b.append([222])
print(b)
b.extend([333])    #此处添加上去的是列表里面的数
print(b)
b.insert(5,'bird')
print(b)

out:
[1, 3, 4, 2, 12, 34, 6, 7, 222]
[1, 3, 4, 2, 12, 34, 6, 7, 222, [222]]
[1, 3, 4, 2, 12, 34, 6, 7, 222, [222], 333]
[1, 3, 4, 2, 12, 'bird', 34, 6, 7, 222, [222], 333]

  

  

#对list进行删、改
b = [1, 35,3, 4, 2, 12, 'bird', 35, 6, 7, 222, [222], 333]
b.pop()    #弹出末尾的
print(b)
b.remove(12)   #移除列表中某个值的第一个匹配项
print(b)
b[1]='first'
print(b)

out;
[1, 35, 3, 4, 2, 12, 'bird', 35, 6, 7, 222, [222]]
[1, 35, 3, 4, 2, 'bird', 35, 6, 7, 222, [222]]
[1, 'first', 3, 4, 2, 'bird', 35, 6, 7, 222, [222]]

  

 

##对list进行查、排序等
b=[1, 3, 4, 2, 3, 6, 7, 222] b.reverse() print(b) b.sort() print(b) b.count(3) print(list(enumerate(b))) #列表中有重复元素,抽取其对应索引的方法 print([i for i,x in enumerate(b) if x==3]) #enumerate(b)是元祖了,而且x==3这里需要的是判断,两个等号 out: [222, 7, 6, 3, 2, 4, 3, 1] [1, 2, 3, 3, 4, 6, 7, 222] [(0, 1), (1, 2), (2, 3), (3, 3), (4, 4), (5, 6), (6, 7), (7, 222)] [2, 3]

 

#list与numpy.array之间的转换
import numpy as np
b=[1,3,5,6]
nb=np.array(b)
print(nb)
print(type(nb))
ob=nb.tolist()
print(ob)
print(type(ob))

out:
[1 3 5 6]
<class 'numpy.ndarray'>
[1, 3, 5, 6]
<class 'list'>

  

  

 

2、元祖tuple

#生成和访问
a=6,
print(a)
b=tuple('ASD')
print(b)
print(b[0])

out:
(6,)
('A', 'S', 'D')
A

  

#元祖里针对元素的增删都是非法的,
#但是可以新建一个变量,利用两个元祖进行相加
#也可以用del语句来删除整个元祖,如del b

 

#元祖的遍历
b=tuple('ASD')
for x in b:
    print(x)
 
out:
A
S
D

  

#字典的遍历、是否含有某个键值、某个值
d={'1':'ff','2':'set','3':'light'}
e={'1':'ff','2':'set','3':'light','i':'cat'}
for key in e:
    print(e[key])
if '2' in e.keys():
    print(e['2'])
if 'cat' in e.values():
    print([k for k,v in e.items() if v=='cat'])

out:
ff
set
light
cat
set
['i']

  

len(d) 返回d中的键值对的数量
d(k) 返回键值k对应的value
d[k]=v 是为键值赋值
del d[k] 删除键值为k的项

   

 

posted on 2019-04-10 17:46  xiaoheizi  阅读(265)  评论(0编辑  收藏  举报