变量是计算机内存中的命名位置.每个变量都可以包含一个数据.与Java不同,Python是一种动态类型语言.因此在使用Jython时也是如此;事先声明数据类型的变量没有完成.数据决定变量的类型,而不是决定可以在其中存储哪些数据的变量类型.
在下面的示例中,为变量分配一个整数值.使用type()内置函数,我们可以验证变量的类型是否为整数.但是,如果为相同的变量分配了一个字符串,则type()函数将字符串作为同一变量的类型.
> x = 10>>> type(x)>>> x = "hello">>> type(x)
这解释了为什么Python被称为动态类型语言.
以下Python内置数据类型也可以用于Jython :
数字
字符串
列表
元组
字典
Python识别数字数据作为数字,可以是整数,具有浮点的实数或复数. String,List和Tuple数据类型称为序列.
Jython数字
在Python中,任何带符号的整数都被称为'int'类型.为了表示一个长整数,附加字母'L'.将整数部分与小数部分分开的小数点数字称为"浮点数".小数部分可以包含使用'E'或'e'以科学记数法表示的指数.
复数也被定义为Python中的数字数据类型.复数包含实部(浮点数)和附加'j'的虚部.
为了表示八进制或十六进制表示中的数字, 0O 或 0X 为其加上前缀.下面的代码块给出了Python中不同数字表示的示例.
int -> 10, 100, -786, 80long -> 51924361L, -0112L, 47329487234Lfloat -> 15.2, -21.9, 32.3+e18, -3.25E+101complex -> 3.14j, 45.j, 3e+26J, 9.322e-36j
Jython Strings
字符串是任意的用单引号(例如'hello'),double(例如"hello")或triple(例如'"hello""o"""hello""")括起来的字符序列.如果字符串的内容跨越多行,则三引号特别有用.
Escape序列字符可以逐字包含在三引号字符串中.以下示例显示了在Python中声明字符串的不同方法.
str = ’hello how are you?’str = "Hello how are you?"str = """this is a long string that is made up of several lines and non-printablecharacters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEswithin the string, whether explicitly given like this within the brackets [ \n ], or justa NEWLINE within the variable assignment will also show up."""
打印时的第三个字符串将给出以下输出.
this is a long string that is made up ofseveral lines and non-printable characters such asTAB ( ) and they will show up that way when displayed.NEWLINEs within the string, whether explicitly given likethis within the brackets [], or just a NEWLINE withinthe variable assignment will also show up.
Jython列表
列表是序列数据类型.它是逗号分隔项的集合,不一定是同一类型,存储在方括号中.可以使用基于零的索引访问List中的单个项目.
以下代码块总结了Python中List的用法.
list1 = ['physics', 'chemistry', 1997, 2000];list2 = [1, 2, 3, 4, 5, 6, 7 ];print "list1[0]: ", list1[0]print "list2[1:5]: ", list2[1:5]
下表描述了一些与Jython列表相关的最常见的Jython表达式.
Jython Expression | Description |
---|---|
len(List) | Length |
List[2]=10 | Updation |
Del List[1] | Deletion |
List.append(20) | Append |
List.insert(1,15) | Insertion |
List.sort() | Sorting |
Jython元组
元组是存储在括号中的逗号分隔数据项的不可变集合.无法删除或修改元组中的元素,也无法向元组集合添加元素.以下代码块显示了元组操作.
tup1 = ('physics','chemistry‘,1997,2000);tup2 = (1, 2, 3, 4, 5, 6, 7 );print "tup1[0]: ", tup1[0]print "tup2[1:5]: ", tup2[1:5]
Jython Dictionary
Jython Dictionary类似于Java Collection框架中的Map类.它是键值对的集合.用逗号分隔的对用大括号括起来. Dictionary对象不遵循从零开始的索引来检索其中的元素,因为它们是通过散列技术存储的.
相同的键在字典对象中不能出现多次.但是,多个键可以具有相同的关联值. Dictionary对象提供的不同功能在下面和下面解释;
dict = {'011':'New Delhi','022':'Mumbai','033':'Kolkata'}print "dict[‘011’]: ",dict['011']print "dict['Age']: ", dict['Age']
下表描述了一些与Dictionary相关的最常见的Jython表达式.
Jython Expression | 描述 |
---|---|
dict.get('011' ) | 搜索 |
len(dict) | 长度 |
dict ['044'] ='Chennai' | 追加 |
del dict ['022'] | 删除 |
dict.keys() | list键 |
dict.values() | 值列表 |
dict.clear() | 删除所有元素 |