pythonu函数 python %u

python字典操作函数

字典是一种通过名字或者关键字引用的得数据结构,其键可以是数字、字符串、元组,这种结构类型也称之为映射。字典类型是Python中唯一内建的映射类型,基本的操作包括如下:

创新互联建站自2013年创立以来,是专业互联网技术服务公司,拥有项目成都做网站、成都网站制作网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元甘孜州做网站,已为上家服务,为甘孜州各地企业和个人服务,联系电话:18980820575

(1)len():返回字典中键—值对的数量;

(2)d[k]:返回关键字对于的值;

(3)d[k]=v:将值关联到键值k上;

(4)del d[k]:删除键值为k的项;

(5)key in d:键值key是否在d中,是返回True,否则返回False。

(6)clear函数:清除字典中的所有项

(7)copy函数:返回一个具有相同键值的新字典;deepcopy()函数使用深复制,复制其包含所有的值,这个方法可以解决由于副本修改而使原始字典也变化的问题

(8)fromkeys函数:使用给定的键建立新的字典,键默认对应的值为None

(9)get函数:访问字典成员

(10)has_key函数:检查字典中是否含有给出的键

(11)items和iteritems函数:items将所有的字典项以列表方式返回,列表中项来自(键,值),iteritems与items作用相似,但是返回的是一个迭代器对象而不是列表

(12)keys和iterkeys:keys将字典中的键以列表形式返回,iterkeys返回键的迭代器

(13)pop函数:删除字典中对应的键

(14)popitem函数:移出字典中的项

(15)setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值

(16)update函数:用一个字典更新另外一个字典

(17) values和itervalues函数:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素

一、字典的创建

1.1 直接创建字典

d={'one':1,'two':2,'three':3}

printd

printd['two']

printd['three']

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

1.2 通过dict创建字典

# _*_ coding:utf-8 _*_

items=[('one',1),('two',2),('three',3),('four',4)]

printu'items中的内容:'

printitems

printu'利用dict创建字典,输出字典内容:'

d=dict(items)

printd

printu'查询字典中的内容:'

printd['one']

printd['three']

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

items中的内容:

[('one',1), ('two',2), ('three',3), ('four',4)]

利用dict创建字典,输出字典内容:

{'four':4,'three':3,'two':2,'one':1}

查询字典中的内容:

或者通过关键字创建字典

# _*_ coding:utf-8 _*_

d=dict(one=1,two=2,three=3)

printu'输出字典内容:'

printd

printu'查询字典中的内容:'

printd['one']

printd['three']

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

输出字典内容:

{'three':3,'two':2,'one':1}

查询字典中的内容:

二、字典的格式化字符串

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3,'four':4}

printd

print"three is %(three)s."%d

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'four':4,'three':3,'two':2,'one':1}

threeis3.

三、字典方法

3.1 clear函数:清除字典中的所有项

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3,'four':4}

printd

d.clear()

printd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'four':4,'three':3,'two':2,'one':1}

{}

请看下面两个例子

3.1.1

# _*_ coding:utf-8 _*_

d={}

dd=d

d['one']=1

d['two']=2

printdd

d={}

printd

printdd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'two':2,'one':1}

{}

{'two':2,'one':1}

3.1.2

# _*_ coding:utf-8 _*_

d={}

dd=d

d['one']=1

d['two']=2

printdd

d.clear()

printd

printdd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'two':2,'one':1}

{}

{}

3.1.2与3.1.1唯一不同的是在对字典d的清空处理上,3.1.1将d关联到一个新的空字典上,这种方式对字典dd是没有影响的,所以在字典d被置空后,字典dd里面的值仍旧没有变化。但是在3.1.2中clear方法清空字典d中的内容,clear是一个原地操作的方法,使得d中的内容全部被置空,这样dd所指向的空间也被置空。

3.2 copy函数:返回一个具有相同键值的新字典

# _*_ coding:utf-8 _*_

x={'one':1,'two':2,'three':3,'test':['a','b','c']}

printu'初始X字典:'

printx

printu'X复制到Y:'

y=x.copy()

printu'Y字典:'

printy

y['three']=33

printu'修改Y中的值,观察输出:'

printy

printx

printu'删除Y中的值,观察输出'

y['test'].remove('c')

printy

printx

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

初始X字典:

{'test': ['a','b','c'],'three':3,'two':2,'one':1}

X复制到Y:

Y字典:

{'test': ['a','b','c'],'one':1,'three':3,'two':2}

修改Y中的值,观察输出:

{'test': ['a','b','c'],'one':1,'three':33,'two':2}

{'test': ['a','b','c'],'three':3,'two':2,'one':1}

删除Y中的值,观察输出

{'test': ['a','b'],'one':1,'three':33,'two':2}

{'test': ['a','b'],'three':3,'two':2,'one':1}

注:在复制的副本中对值进行替换后,对原来的字典不产生影响,但是如果修改了副本,原始的字典也会被修改。deepcopy函数使用深复制,复制其包含所有的值,这个方法可以解决由于副本修改而使原始字典也变化的问题。

# _*_ coding:utf-8 _*_

fromcopyimportdeepcopy

x={}

x['test']=['a','b','c','d']

y=x.copy()

z=deepcopy(x)

printu'输出:'

printy

printz

printu'修改后输出:'

x['test'].append('e')

printy

printz

运算输出:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

输出:

{'test': ['a','b','c','d']}

{'test': ['a','b','c','d']}

修改后输出:

{'test': ['a','b','c','d','e']}

{'test': ['a','b','c','d']}

3.3 fromkeys函数:使用给定的键建立新的字典,键默认对应的值为None

# _*_ coding:utf-8 _*_

d=dict.fromkeys(['one','two','three'])

printd

运算输出:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':None,'two':None,'one':None}

或者指定默认的对应值

# _*_ coding:utf-8 _*_

d=dict.fromkeys(['one','two','three'],'unknow')

printd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':'unknow','two':'unknow','one':'unknow'}

3.4 get函数:访问字典成员

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printd.get('one')

printd.get('four')

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

1

None

注:get函数可以访问字典中不存在的键,当该键不存在是返回None

3.5 has_key函数:检查字典中是否含有给出的键

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printd.has_key('one')

printd.has_key('four')

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

True

False

3.6 items和iteritems函数:items将所有的字典项以列表方式返回,列表中项来自(键,值),iteritems与items作用相似,但是返回的是一个迭代器对象而不是列表

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

list=d.items()

forkey,valueinlist:

printkey,':',value

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

three :3

two :2

one :1

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

it=d.iteritems()

fork,vinit:

print"d[%s]="%k,v

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

d[three]=3

d[two]=2

d[one]=1

3.7 keys和iterkeys:keys将字典中的键以列表形式返回,iterkeys返回键的迭代器

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printu'keys方法:'

list=d.keys()

printlist

printu'\niterkeys方法:'

it=d.iterkeys()

forxinit:

printx

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

keys方法:

['three','two','one']

iterkeys方法:

three

two

one

3.8 pop函数:删除字典中对应的键

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

d.pop('one')

printd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

{'three':3,'two':2}

3.9 popitem函数:移出字典中的项

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

d.popitem()

printd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

{'two':2,'one':1}

3.10 setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printd.setdefault('one',1)

printd.setdefault('four',4)

printd

运算结果:

{'three':3,'two':2,'one':1}

{'four':4,'three':3,'two':2,'one':1}

3.11 update函数:用一个字典更新另外一个字典

# _*_ coding:utf-8 _*_

d={

'one':123,

'two':2,

'three':3

}

printd

x={'one':1}

d.update(x)

printd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':123}

{'three':3,'two':2,'one':1}

3.12 values和itervalues函数:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素

# _*_ coding:utf-8 _*_

d={

'one':123,

'two':2,

'three':3,

'test':2

}

printd.values()

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

[2,3,2,123]

python这段代码中u什么意思?

以u或U开头的字符串表示unicode字符串,

print时,就相当于print "游戏结果\n成绩列表",字符串中,转义字符会进行转义。

输出结果就是:

游戏结果

成绩列表

别外一种用法,如果想直接输出"游戏结果\n成绩列表",就写成:

aa=(r"游戏结果\n成绩列表")

print(aa)

这样,\n就不会进行转义,方便输出处理反斜杠,

这样输出结果就是:

游戏结果\n成绩列表

python 截取指定字符前后的所有字符的函数

可以参考下面的代码:

#!/usr/bin/python

# encoding: utf-8

# filename: baiduzhidao.py

ln = "4564612131856+654654654654"

print ln.split("+")

#~ Result:

#~ python -u "baiduzhidao.py"

#~ ['4564612131856', '654654654654']

#~ Exit code: 0    Time: 0.052

Python在设计上坚持了清晰划一的风格,这使得Python成为一门易读、易维护,并且被大量用户所欢迎的、用途广泛的语言,设计者开发时总的指导思想是,对于一个特定的问题,只要有一种最好的方法来解决就好了。

Python本身被设计为可扩充的。并非所有的特性和功能都集成到语言核心。Python提供了丰富的API和工具,以便程序员能够轻松地使用C语言、C++、Cython来编写扩充模块。

Python是完全面向对象的语言。函数、模块、数字、字符串都是对象。并且完全支持继承、重载、派生、多继承,有益于增强源代码的复用性。

扩展资料:

python参考函数

vars(obj) 返回一个object的name space。用dictionary表示

locals() 返回一个局部name space,用dictionary表示

globals() 返回一个全局name space,用dictionary表示

type(obj) 查看一个obj的类型

isinstance(obj,cls) 查看obj是不是cls的instance

issubclass(subcls,supcls) 查看subcls是不是supcls的子类

参考资料来源:百度百科-Python (计算机程序设计语言)

python3--内置函数

python的常用内置函数

1.abs() 函数返回数字的绝对值

abs(-40)=40

2. dict() 函数用于创建一个字典

dict()

{}      #创建一个空字典类似于u={},字典的存取方式一般为key-value

例如u = {"username":"tom",  "age":18}

3. help() 函数用于查看函数或模块用途的详细说明

help('math')查看math模块的用处

a=[1,2,3,4]

help(a)查看列表list帮助信息

4.dir()获得当前模块的属性列表

dir(help)

['__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

5.min() 方法返回给定参数的最小值 /参数可以为序列

a=  min(10,20,30,40)

a

10

6. next() 返回迭代器的下一个项目

it = iter([1, 2, 3, 4, 5])

next(it)

1

next(it)

2

7. id() 函数用于获取对象的内存地址

a=12

id(a)

1550569552

8.enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

a=["tom","marry","leblan"]

list(enumerate(a))

[(0, 'tom'), (1, 'marry'), (2, 'leblan')]

9. oct() 函数将一个整数转换成8进制字符串

oct(15)

'0o17'

oct(10)

'0o12'

10. bin() 返回一个整数 int 或者长整数 long int 的二进制表示

bin(10)

'0b1010'

bin(15)

'0b1111'

11.eval() 函数用来执行一个字符串表达式,并返回表达式的值

eval('2+2')

4

12.int() 函数用于将一个字符串会数字转换为整型

int(3)

3

int(3.6)

3

int(3.9)

3

int(4.0)

4

13.open() 函数用于打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写

f=open('test.txt')

14.str() 函数将对象转化为适于人阅读的形式

str(3)

'3'

15. bool() 函数用于将给定参数转换为布尔类型,如果没有参数,返回 False

bool()

False

bool(1)

True

bool(10)

True

bool(10.0)

True

16.isinstance() 函数来判断一个对象是否是一个已知的类型

a=5

isinstance(a,int)

True

isinstance(a,str)

False

17. sum() 方法对系列进行求和计算

sum([1,2,3],5)

11

sum([1,2,3])

6

18. super() 函数用于调用下一个父类(超类)并返回该父类实例的方法。super 是用来解决多重继承问题的,直接用类名调用父类方法

class   User(object):

  def__init__(self):

class Persons(User):

        super(Persons,self).__init__()

19. float() 函数用于将整数和字符串转换成浮点数

float(1)

1.0

float(10)

10.0

20. iter() 函数用来生成迭代器

a=[1,2,3,4,5,6]

iter(a)

for i in iter(a):

...         print(i)

...

1

2

3

4

5

6

21.tuple 函数将列表转换为元组

a=[1,2,3,4,5,6]

tuple(a)

(1, 2, 3, 4, 5, 6)

22.len() 方法返回对象(字符、列表、元组等)长度或项目个数

s = "playbasketball"

len(s)

14

a=[1,2,3,4,5,6]

len(a)

6

23. property() 函数的作用是在新式类中返回属性值

class User(object):

 def __init__(self,name):

          self.name = name

def get_name(self):

          return self.get_name

@property

 def name(self):

         return self_name

24.type() 函数返回对象的类型

25.list() 方法用于将元组转换为列表

b=(1,2,3,4,5,6)

list(b)

[1, 2, 3, 4, 5, 6]

26.range() 函数可创建一个整数列表,一般用在 for 循环中

range(10)

range(0, 10)

range(10,20)

range(10, 20)

27. getattr() 函数用于返回一个对象属性值

class w(object):

...             s=5

...

a = w()

getattr(a,'s')

5

28. complex() 函数用于创建一个复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数

complex(1,2)

(1+2j)

complex(1)

(1+0j)

complex("1")

(1+0j)

29.max() 方法返回给定参数的最大值,参数可以为序列

b=(1,2,3,4,5,6)

max(b)

6

30. round() 方法返回浮点数x的四舍五入值

round(10.56)

11

round(10.45)

10

round(10.45,1)

10.4

round(10.56,1)

10.6

round(10.565,2)

10.56

31. delattr 函数用于删除属性

class Num(object):

...    a=1

...    b=2

...    c=3.

.. print1 = Num()

print('a=',print1.a)

a= 1

print('b=',print1.b)

b= 2

print('c=',print1.c)

c= 3

delattr(Num,'b')

print('b=',print1.b)

Traceback (most recent call last):  File "", line 1, inAttributeError: 'Num' object has no attribute 'b'

32. hash() 用于获取取一个对象(字符串或者数值等)的哈希值

hash(2)

2

hash("tom")

-1675102375494872622

33. set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

a= set("tom")

b = set("marrt")

a,b

({'t', 'm', 'o'}, {'m', 't', 'a', 'r'})

ab#交集

{'t', 'm'}

a|b#并集

{'t', 'm', 'r', 'o', 'a'}

a-b#差集

{'o'}

太全了!Python3常用内置函数总结

数学相关

abs(a) : 求取绝对值。abs(-1)

max(list) : 求取list最大值。max([1,2,3])

min(list) : 求取list最小值。min([1,2,3])

sum(list) : 求取list元素的和。 sum([1,2,3]) 6

sorted(list) : 排序,返回排序后的list。

len(list) : list长度,len([1,2,3])

divmod(a,b): 获取商和余数。 divmod(5,2) (2,1)

pow(a,b) : 获取乘方数。pow(2,3) 8

round(a,b) : 获取指定位数的小数。a代表浮点数,b代表要保留的位数。round(3.1415926,2) 3.14

range(a[,b]) : 生成一个a到b的数组,左闭右开。range(1,10) [1,2,3,4,5,6,7,8,9]

类型转换

int(str) : 转换为int型。int('1') 1

float(int/str) : 将int型或字符型转换为浮点型。float('1') 1.0

str(int) : 转换为字符型。str(1) '1'

bool(int) : 转换为布尔类型。 str(0) False str(None) False

bytes(str,code) : 接收一个字符串,与所要编码的格式,返回一个字节流类型。bytes('abc', 'utf-8') b'abc' bytes(u'爬虫', 'utf-8') b'xe7x88xacxe8x99xab'

list(iterable) : 转换为list。 list((1,2,3)) [1,2,3]

iter(iterable): 返回一个可迭代的对象。 iter([1,2,3]) list_iterator object at 0x0000000003813B00

dict(iterable) : 转换为dict。 dict([('a', 1), ('b', 2), ('c', 3)]) {'a':1, 'b':2, 'c':3}

enumerate(iterable) : 返回一个枚举对象。

tuple(iterable) : 转换为tuple。 tuple([1,2,3]) (1,2,3)

set(iterable) : 转换为set。 set([1,4,2,4,3,5]) {1,2,3,4,5} set({1:'a',2:'b',3:'c'}) {1,2,3}

hex(int) : 转换为16进制。hex(1024) '0x400'

oct(int) : 转换为8进制。 oct(1024) '0o2000'

bin(int) : 转换为2进制。 bin(1024) '0b10000000000'

chr(int) : 转换数字为相应ASCI码字符。 chr(65) 'A'

ord(str) : 转换ASCI字符为相应的数字。 ord('A') 65

相关操作

eval****() : 执行一个表达式,或字符串作为运算。 eval('1+1') 2

exec() : 执行python语句。 exec('print("Python")') Python

filter(func, iterable) : 通过判断函数fun,筛选符合条件的元素。 filter(lambda x: x3, [1,2,3,4,5,6]) filter object at 0x0000000003813828

map(func, *iterable) : 将func用于每个iterable对象。 map(lambda a,b: a+b, [1,2,3,4], [5,6,7]) [6,8,10]

zip(*iterable) : 将iterable分组合并。返回一个zip对象。 list(zip([1,2,3],[4,5,6])) [(1, 4), (2, 5), (3, 6)]

type():返回一个对象的类型。

id(): 返回一个对象的唯一标识值。

hash(object):返回一个对象的hash值,具有相同值的object具有相同的hash值。 hash('python') 7070808359261009780

help():调用系统内置的帮助系统。

isinstance():判断一个对象是否为该类的一个实例。

issubclass():判断一个类是否为另一个类的子类。

globals() : 返回当前全局变量的字典。

next(iterator[, default]) : 接收一个迭代器,返回迭代器中的数值,如果设置了default,则当迭代器中的元素遍历后,输出default内容。

reversed(sequence) : 生成一个反转序列的迭代器。 reversed('abc') ['c','b','a']

本文标题:pythonu函数 python %u
地址分享:https://www.cdcxhl.com/article0/dodccoo.html

成都网站建设公司_创新互联,为您提供响应式网站动态网站网站导航网页设计公司网站建设建站公司

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

微信小程序开发