当前位置: 首页 > news >正文

东莞石龙网站建设企拓客软件多少钱

东莞石龙网站建设,企拓客软件多少钱,新媒体营销的概念是什么,经营性网站备案信息申请python基础运用例子 1、⼀⾏代码交换 a , b :a, b b, a2、⼀⾏代码反转列表 l[::-1]3、合并两个字典 res {**dict1, **dict2}**操作符合并两个字典for循环合并dict(a, **b) 的方式dict(a.items() b.items()) 的方式dict.update(other_dict) 的方式 4、⼀⾏代码列…

python基础运用例子

    • 1、⼀⾏代码交换 a , b :`a, b = b, a`
    • 2、⼀⾏代码反转列表 l[::-1]
    • 3、合并两个字典 res = {**dict1, **dict2}
      • **操作符
      • 合并两个字典
        • for循环合并
        • dict(a, **b) 的方式
        • dict(a.items() + b.items()) 的方式
        • dict.update(other_dict) 的方式
    • 4、⼀⾏代码列表去重set([1,1,1])
    • ⼀⾏代码求多个列表中的最⼤值
      • max
    • ⼀⾏代码⽣成逆序序列
  • python内置函数
    • all()函数 all([1, 0, 3, 6])
    • any()函数
    • bool函数
  • 面向对象
    • 构造方法 def __init__(self, name)
    • "__成员名"定义私有成员
    • 内部私有成员的调用 同Java、C++通过公有成员函数调用
    • 创建对象 构造函数两个以上参数,不指明参数就要按顺序,想不按顺序就可以声明参数
    • str()函数和repr() 函数
      • str()函数
      • repr() 函数
      • __repr
  • 格式化字符串
    • %-- 'Hello %s' % 'Python'
    • format()-- '{0} {1}'.format('Hello', 'Python')
    • f-string-- f'User {username} has logged in and did an action {action}.'

1、⼀⾏代码交换 a , b :a, b = b, a

a = 1
b = 2
a, b = b, a
print(a, b)  # 2 1

2、⼀⾏代码反转列表 l[::-1]

l=[1,2,3]
print(l[::-1] ) # [3,2,1]

3、合并两个字典 res = {**dict1, **dict2}

# {**{'a':1,'b':2}, **{'c':3}}
d1={'a':1,'b':2}
d2={'c':3}
print({**d1,**d2})# {'a': 1, 'b': 2, 'c': 3}

**操作符

函数形参汇聚 —— 打包
*args 和 **kwargs 常作为 魔法变量 出现于函数定义中,用于将不定量实参传递给函数。其中:

*args 的本质是将 位置形参 汇集为 tuple 然后由变量 args 接收,:

>>> def test1(x, *args):''' 将除首个元素 x 外的位置参数 args 汇聚为一个 tuple '''print(x, args) >>> test1('a', 'b', 'c', 'd')
'a' ('b', 'c', 'd')>>> test1(1, 2, 3, 4)
1 (2, 3, 4)

**kwargs 的本质则是将 关键字形参 汇集为 dict 然后由变量 kwargs 接收:

>>> def test2(**kwargs):''' 将所有关键字参数汇聚为 dict ''' for key, value in kwargs.items():print("{0} = {1}".format(key, value))>>> test2(a=1, b=2, c=3, d=4)
a = 1
b = 2
c = 3
d = 4

注意,单星操作符 * 无法汇集关键字参数,双星操作符 ** 才可以

合并两个字典

for循环合并

a = {1: 'a', 2: 'aa'}
b = {3: 'aaa', 4: 'aaaa'}
for k, v in b.items():a[k] = v# print(k)print(a)
# {1: 'a', 2: 'aa', 3: 'aaa', 4: 'aaaa'}

dict(a, **b) 的方式

d1={'a':1,'b':2}
d2={'c':3}
print(dict(d1,**d2))

dict(a.items() + b.items()) 的方式

dict.items() 能够得到一个包含以该字典的键与值为元素组成的元组的列表:

>>> a = {1: 'a', 2: 'aa'}
>>> a.items()
[(1, 'a'), (2, 'aa')]

两个列表实现 + 运算, 即是将两个列表合并, 而 dict() 方法可以接收类似于上面例子中的数据结构来组装并返回一个字典类型的数据, 所以我们可以使用 dict(a.items() + b.items()) 的方法来合并 a、 b 两个字典:

>>> a = {1: 'a', 2: 'aa'}
>>> b = {3: 'aaa', 4: 'aaaa'}
>>> dict(a.items() + b.items())
{1: 'a', 2: 'aa', 3: 'aaa', 4: 'aaaa'}

dict.update(other_dict) 的方式

直接调用字典的 update() 方法, 同样可以将两个字典合并:

>>> a = {1: 'a', 2: 'aa'}
>>> b = {3: 'aaa', 4: 'aaaa'}
>>> a.update(b)
>>> a
{1: 'a', 2: 'aa', 3: 'aaa', 4: 'aaaa'}

4、⼀⾏代码列表去重set([1,1,1])

set([1,2,2,3,3,3]) 
# {1, 2, 3}

⼀⾏代码求多个列表中的最⼤值

a=max(max([ [1,2,3], [5,1], [4] ], key=lambda v: max(v)))
print(a)
# 5

解释:比较列表大小的规则是 根据 每个列表中最大值
传入命名参数key,其为一个函数,用来指定取最大值的方法

max

max函数的作用是返回可迭代序列中的最大项或两个或多个参数中的最大项
多个参数中的最大项

print(max(1,2,3,4))  # 输出4

注意:函数至少传入两个参数,但是有只传入一个参数的例外,此时参数必须为可迭代对象,返回的是可迭代对象中的最大元素。
可迭代对象,如s = '12345'[1,2,3,4,5]

s = '12345'print(max(s))
  1. 以默认的比较方式直接获得最大项
# 求序列最大值
>>> max([1,2,3,4,5])
5
  1. 指定比较方式func获取最大值
# 元组之间的比较默认是从左到右比较
>>> max([(1, '5'), (2, '4'), (3, '3'), (4, '2'), (5, '1')])
(5, '1')
# 我自定义的比较方式是比较第二个键值的大小
>>> max([(1, '5'), (2, '4'), (3, '3'), (4, '2'), (5, '1')], key=lambda x: x[1])
(1, '5')
s = [{'name': 'sumcet', 'age': 18},{'name': 'bbu', 'age': 11}]
a = max(s, key=lambda x: x['age'])
print(a)
# {'name': 'sumcet', 'age': 18}# 输出
# {'name': 'sumcet', 'age': 18}

⼀⾏代码⽣成逆序序列

list(range(10,-1,-1))
#输出结果为:[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

python内置函数

all()函数 all([1, 0, 3, 6])

接受⼀个迭代器,如果迭代器的 所有元素 都为真,那么返回 True,否则返回 False
python内置函数all可用于判断传入的可迭代参数 iterable 中的所有元素是否都为True,如果是则返回True,反之返回False。如果可迭代对象是空的,也会返回True

res = all([1, 0, 3, 6])
print(res)
# false
res = all([1,2,3])
print(res)
# true
print(all([True, 4, 7]))  # True
print(all((True, False)))  # False, 因为有一个元素不是Trueprint(all([]))  # True

any()函数

接受⼀个迭代器,如果迭代器⾥ ⾄少有⼀个 元素为真,那么返回 True,否则返回 False

print(any([0,0,0,[]]))
# false
print(any([0,0,1]))
# true

bool函数

  • 参数如果缺省,则返回False
  • 传入布尔类型,按原值返回
  • 传入字符串,空字符串返回False,否则返回True
  • 传入数值时,0值返回False,否则返回True
  • 传入元组,列表,字典等对象时,元素个数为空返回False, 否则返回True
  • Tips:
    字符串的’0’,是字符串,但不是空字符串,因此返回bool(‘0’)返回True
>>>bool()
False
>>> bool(0)
False
>>> bool(1)
True
>>> bool(2)
True
>>> issubclass(bool, int)  # bool 是 int 子类
True
print(bool([0,0,0]))
# Out[1]:True
print(bool([]))
# Out[2]: False
print(bool([1,0,1]))
# Out[3]: True

面向对象

构造方法 def init(self, name)

构造方法 init() 会在类实例化时自动调用。无论构造方法还是其他方法都需要将 self 作为第一个参数,它代表类的实例。

class Cat:# 属性color = 'black'# 构造方法def __init__(self, name):self.name = name# 自定义方法def eat(self, food):self.food = foodprint(self.name, '正在吃'+food)

"__成员名"定义私有成员

面 Cat 类中定义的属性和方法都是公开的,除此之外我们还可以定义私有属性和方法,声明方式为:在属性名或方法名前加两条下划线,示例如下所示:

class Cat:__cid = '1'def __run(self):pass

需要强调一点是:外部不能访问私有属性和调用私有方法,自然 Cat.__cid 是会报错的。

内部私有成员的调用 同Java、C++通过公有成员函数调用


class Cat:__cid = '1'def __run(self, speed):print('__cid是'+self.__cid+'的猫', '以'+speed+'的速度奔跑')def run(self, speed):self.__run(speed)c.run('50迈')

创建对象 构造函数两个以上参数,不指明参数就要按顺序,想不按顺序就可以声明参数

 # 创建对象
c = Cat('Tom')
class Student():def __init__(self, id, name):self.id = idself.name = name# xiaoming = Student(id='001', name='xiaoming')
xiaoming = Student('001', 'xiaoming')
xiaoming = Student(name='xiaoming', id='002')

str()函数和repr() 函数

class Student():def __init__(self, id, name):self.id = idself.name = namedef __repr__(self):return 'id = ' + self.id + ', name = ' + self.name
# xiaoming = Student(id='001', name='xiaoming')
xiaoming = Student('001', 'xiaoming')
xiaoming = Student(name='xiaoming', id='002')
print(xiaoming)
# id = 001, name = xiaoming
ascii(xiaoming)
# 'id = 001, name = xiaoming'

str()函数

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

s = 'RUNOOB'
print(str(s))
# 'RUNOOB'
dict = {'runoob': 'runoob.com', 'google': 'google.com'};
print(str(dict))
# "{'google': 'google.com', 'runoob': 'runoob.com'}"

在这里插入图片描述

repr() 函数

repr() 函数将对象转化为供解释器读取的形式

s = 'RUNOOB'
print(repr(s))
# "'RUNOOB'"
dict = {'runoob': 'runoob.com', 'google': 'google.com'};
print( repr(dict))
# "{'google': 'google.com', 'runoob': 'runoob.com'}"

在这里插入图片描述
repr() 方法可以将读取到的格式字符,比如换行符、制表符,转化为其相应的转义字符。

# coding=UTF-8s="物品\t单价\t数量\n包子\t1\t2"
print(s)
print(repr(s))

在这里插入图片描述
一个面向用户一个面向机器
repr(str) 输出字符串会加上引号''

str = '3.14'
print('原型:', str, '类型:', type(str), '长度:',len(str))# repr()转换
repr1= repr(str)
print('repr()转换:', repr1, '类型:',  type(repr1),'长度:', len(repr1))
# str()转换
s = '3.14' #使用str()函数要注意字符串不要占用变量名str,否则报错
str1 = str(s)
print('str()转换:', str1, '类型:',  type(str1),'长度:', len(str1))

在这里插入图片描述

在这里插入图片描述

print(str(3.14))
print(str('3.14'))
print(repr(3.14))
print(repr('3.14'))

在这里插入图片描述

输出字典的效果一致

__repr

class A(object):def __init__(self, name, age):self.name = nameself.age = agedef __repr__(self):return f'name:{self.name},age:{self.age}'my_list = [A('张三', 8), A('李四', 9)]
print(my_list)

在这里插入图片描述

class A(object):def __init__(self, name, age):self.name = nameself.age = agedef __str__(self):return f'name:{self.name},age:{self.age}'my_list = [A('张三', 8), A('李四', 9)]
print(my_list)

在这里插入图片描述

运行可以发现,有没有__str__函数输出结果一致,
通过简单的对⽐,我们发现,直接输出对象,调⽤的__repr__ ⽅法。
另外还需要注意的是,如果将对象放在容器中进⾏输出,调⽤的是__repr__ ⽅法。

总结
Python 中的 str 和 repr ⽅法都是⽤来显示的,即描述对象信息的。
如果重写__str__ ⽅法,也重写了 repr ⽅法时,则默认调⽤ __repr__⽅法。

原文链接:https://blog.csdn.net/qq_41564918/article/details/109014354

格式化字符串

%-- ‘Hello %s’ % ‘Python’

当我们需要输出的内容中含有变量时,比如:Hello xxx,xxx 为变量,此时便需要一种格式化字符串的方式,Python 使用 % 格式化字符串,常用占位符如下表所示:

占位符 描述
%s 格式化字符串
%d 格式化整数
%f 格式化浮点数
以字符串为例,如下所示:

print('Hello %s' % 'Python')

输出结果:

Hello Python

format()-- ‘{0} {1}’.format(‘Hello’, ‘Python’)

我们也可以使用字符串的 format() 方法进行格式化,先看下示例:

print('{0} {1}'.format('Hello', 'Python'))

这种方式是

用传入的参数依次替换字符串内的占位符{0}{1} ...

f-string-- f’User {username} has logged in and did an action {action}.’

f-string 除了提供强大的格式化功能之外,还是这三种格式化方式中性能最高的实现。

# %s
username = 'tom'
action = 'payment'
message = 'User %s has logged in and did an action %s.' % (username, action)
print(message)# format
username = 'tom'
action = 'payment'
message = 'User {} has logged in and did an action {}.'.format(username, action)
print(message)# f-string
username = 'tom'
action = 'payment'
message = f'User {username} has logged in and did an action {action}.'
print(message)print(f"{2 * 3}")
# 6comedian = {'name': 'Tom', 'age': 20}
print(f"The comedian is {comedian['name']}, aged {comedian['age']}.")
# The comedian is Tom, aged 20.

相比于常见的字符串格式符 %s 或 format 方法,f-strings 直接在占位符中插入变量显得更加方便,也更好理解。
方便的转换器

f-string 是当前最佳的拼接字符串的形式,拥有更强大的功能,我们再来看一下 f-string 的结构。

f ’ < text> { < expression> <optional !s, !r, or !a> } < text> … ’

其中 ‘!s’ 调用表达式上的 str(),‘!r’ 调用表达式上的 repr(),‘!a’ 调用表达式上的 ascii().

默认情况下,f-string 将使用 str(),但如果包含转换标志 !r,则可以使用 repr()
没有很懂 !r 这些转化标志 ,但f-string 应该是可以把数字转化为字符串,为什么呢

class Person:def __init__(self, name, age):self.name = nameself.age = agedef __str__(self):return f'str - name: {self.name}, age: {self.age}'def __repr__(self):return f'repr - name: {self.name}, age: {self.age}'p = Person('tom', 20)
print(f'{p}')
# str - name: tom, age: 20print(f'{p!r}')
# repr - name: tom, age: 20
# 转换标志 !a
a = 'a string'
print(f'{a!a}')
# "'a string'"
# 等价于
print(f'{repr(a)}')
# "'a string'"
class Student():def __init__(self, id, name):self.id = idself.name = namedef __repr__(self):return 'id = ' + self.id + ', name = ' + self.name
# xiaoming = Student(id='001', name='xiaoming')
xiaoming = Student('001', 'xiaoming')
xiaoming = Student(name='xiaoming', id='002')
print(xiaoming)
class A(object):def __init__(self, name, age):self.name = nameself.age = agedef __repr__(self):return f'name:{self.name},age:{self.age}'# def __repr__(self):#     return 'name = ' + self.name + ', age = ' + self.agemy_list = A('张三', 8)
print(my_list)
my_list = [A('张三', 8), A('李四', 9)]
print(my_list)

在这里插入图片描述

	def __repr__(self):return f'name:{self.name},age:{self.age}'# def __repr__(self):#     return 'name = ' + self.name + ', age = ' + self.age

用下面这种输出字符串,只能接收字符串拼接,即需要输出的参数都是字符串类型,否则报错,
但用上面这种,f-string大概是可以将int类型转化位字符串类型


文章转载自:
http://pastureland.xxhc.cn
http://minify.xxhc.cn
http://diagnosis.xxhc.cn
http://tetramethylene.xxhc.cn
http://bangka.xxhc.cn
http://fractionary.xxhc.cn
http://protozoan.xxhc.cn
http://superficialize.xxhc.cn
http://offaly.xxhc.cn
http://quirky.xxhc.cn
http://personalize.xxhc.cn
http://superexcellent.xxhc.cn
http://gloominess.xxhc.cn
http://enzyme.xxhc.cn
http://posteriorly.xxhc.cn
http://videoland.xxhc.cn
http://weakness.xxhc.cn
http://dialyse.xxhc.cn
http://subnitrate.xxhc.cn
http://broad.xxhc.cn
http://chiropteran.xxhc.cn
http://phantomlike.xxhc.cn
http://cumulocirrus.xxhc.cn
http://streptonigrin.xxhc.cn
http://psychohistorical.xxhc.cn
http://percolator.xxhc.cn
http://nun.xxhc.cn
http://details.xxhc.cn
http://rustiness.xxhc.cn
http://scorebook.xxhc.cn
http://duramater.xxhc.cn
http://fitup.xxhc.cn
http://earbender.xxhc.cn
http://glauconitic.xxhc.cn
http://onr.xxhc.cn
http://resolutive.xxhc.cn
http://upu.xxhc.cn
http://rapporteur.xxhc.cn
http://pasquinade.xxhc.cn
http://arthritic.xxhc.cn
http://entelechy.xxhc.cn
http://yield.xxhc.cn
http://calciphobic.xxhc.cn
http://lanuginose.xxhc.cn
http://eftpos.xxhc.cn
http://cetane.xxhc.cn
http://pippip.xxhc.cn
http://unlet.xxhc.cn
http://malines.xxhc.cn
http://sext.xxhc.cn
http://brandyball.xxhc.cn
http://turnipy.xxhc.cn
http://archetypal.xxhc.cn
http://koppa.xxhc.cn
http://dragnet.xxhc.cn
http://primitive.xxhc.cn
http://devaluation.xxhc.cn
http://skimeister.xxhc.cn
http://coprostasis.xxhc.cn
http://colocynth.xxhc.cn
http://reinject.xxhc.cn
http://trustworthy.xxhc.cn
http://shelly.xxhc.cn
http://knothole.xxhc.cn
http://mopoke.xxhc.cn
http://door.xxhc.cn
http://yean.xxhc.cn
http://schizoidia.xxhc.cn
http://spirally.xxhc.cn
http://spraddle.xxhc.cn
http://amidocyanogen.xxhc.cn
http://raggy.xxhc.cn
http://cranialgia.xxhc.cn
http://feeble.xxhc.cn
http://counterclaim.xxhc.cn
http://savable.xxhc.cn
http://consignee.xxhc.cn
http://dermatotherapy.xxhc.cn
http://reinflate.xxhc.cn
http://verdure.xxhc.cn
http://abuse.xxhc.cn
http://luluai.xxhc.cn
http://conflagrant.xxhc.cn
http://withering.xxhc.cn
http://bren.xxhc.cn
http://polluting.xxhc.cn
http://nostalgic.xxhc.cn
http://quench.xxhc.cn
http://pharaoh.xxhc.cn
http://lizardite.xxhc.cn
http://swipes.xxhc.cn
http://remilitarize.xxhc.cn
http://whistleable.xxhc.cn
http://blackball.xxhc.cn
http://stumblingly.xxhc.cn
http://timpano.xxhc.cn
http://editola.xxhc.cn
http://outwardness.xxhc.cn
http://tea.xxhc.cn
http://pedestrian.xxhc.cn
http://www.dt0577.cn/news/64669.html

相关文章:

  • 网站开发培训要多少钱二级域名在线扫描
  • 寮步营销型网站建设网站搜索引擎优化方案的案例
  • 河南郑州做网站h汉狮谷歌外贸
  • 小程序开发费用计入什么科目seo免费优化工具
  • be设计网站10条重大新闻
  • 玉泉路网站建设如何查询百度收录情况
  • 手表网站官网广东病毒感染最新消息
  • wordpress 旋转加载seo建站要求
  • 杭州网站建设官网蓝韵网络长沙网站定制公司
  • c2c网站建设费用最火的网络销售平台
  • 怎么自己搭建网站营销方案模板
  • 即墨网站建设哪家好网站内容seo
  • seo优化评论搜索引擎优化入门
  • wordpress php7 500北京seo公司哪家好
  • 哪个学校有网站建设360搜索引擎下载
  • 网络营销搜索引擎优化大师官网入口
  • 夏天做那些网站致富精准引流获客软件
  • 网站列表页框架布局原则快速优化工具
  • 网站建设系统 开源网址seo关键词
  • 一套网站设计多少钱郑州专业的网站公司
  • jsp做网站的书淘宝客推广有效果吗
  • 商城网站前台html模板成都seo优化公司排名
  • 做网站的如何找业务自助建站官网
  • 网站分类目录深圳百度推广客服
  • 南京高端网站制作公司关键词提取
  • 给别人做网站用做假酒验证seo诊断
  • 做网站软件下载宁波网络推广平台
  • 网站专业术语中seo意思是商业软文怎么写
  • 晋州 网站建设 网络推广百度客服人工电话24
  • 要想用谷歌访问外国网站怎么做搜索排名优化公司