详解Python中的元组与逻辑运算符

详解Python中的元组与逻辑运算符,第1张

概述Python元组元组是另一个数据类型,类似于List(列表)。元组用\"()\"标识。内部元素用逗号隔开。但是元素不能二次赋值,相当于只读列表。

Python元组
元组是另一个数据类型,类似于List(列表)。
元组用"()"标识。内部元素用逗号隔开。但是元素不能二次赋值,相当于只读列表。

#!/usr/bin/python# -*- Coding: UTF-8 -*-tuple = ( 'abcd',786,2.23,'john',70.2 )tinytuple = (123,'john')print tuple # 输出完整元组print tuple[0] # 输出元组的第一个元素print tuple[1:3] # 输出第二个至第三个的元素 print tuple[2:] # 输出从第三个开始至列表末尾的所有元素print tinytuple * 2 # 输出元组两次print tuple + tinytuple # 打印组合的元组

以上实例输出结果:

('abcd',70.2)abcd(786,2.23)(2.23,70.2)(123,123,'john')('abcd',70.2,'john')

以下是元组无效的,因为元组是不允许更新的。而列表是允许更新的:

#!/usr/bin/python# -*- Coding: UTF-8 -*-tuple = ( 'abcd',70.2 )List = [ 'abcd',70.2 ]tuple[2] = 1000 # 元组中是非法应用List[2] = 1000 # 列表中是合法应用

Python逻辑运算符
Python语言支持逻辑运算符,以下假设变量a为10,变量b为20:


以下实例演示了Python所有逻辑运算符的 *** 作:

#!/usr/bin/pythona = 10b = 20c = 0if ( a and b ):  print "line 1 - a and b are true"else:  print "line 1 - Either a is not true or b is not true"if ( a or b ):  print "line 2 - Either a is true or b is true or both are true"else:  print "line 2 - Neither a is true nor b is true"a = 0if ( a and b ):  print "line 3 - a and b are true"else:  print "line 3 - Either a is not true or b is not true"if ( a or b ):  print "line 4 - Either a is true or b is true or both are true"else:  print "line 4 - Neither a is true nor b is true"if not( a and b ):  print "line 5 - Either a is not true or b is not true or both are not true"else:  print "line 5 - a and b are true"

以上实例输出结果:

line 1 - a and b are trueline 2 - Either a is true or b is true or both are trueline 3 - Either a is not true or b is not trueline 4 - Either a is true or b is true or both are trueline 5 - Either a is not true or b is not true or both are not true

总结

以上是内存溢出为你收集整理的详解Python中的元组与逻辑运算符全部内容,希望文章能够帮你解决详解Python中的元组与逻辑运算符所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1204897.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存