目录

Jython - Variables and 数据类型

变量是计算机内存中的命名位置。 每个变量都可以包含一个数据。 与Java不同,Python是一种动态类型语言。 因此在使用Jython时也是如此; 事先声明数据类型的变量没有完成。 数据决定变量的类型,而不是决定哪些数据可以存储在其中的变量类型。

在以下示例中,为变量分配了一个整数值。 使用type()内置函数,我们可以验证变量的类型是否为整数。 但是,如果为同一个变量分配了一个字符串,那么type()函数将string作为同一个变量的类型。

> x = 10
>>> type(x)
<class 'int'>
>>> x = "hello"
>>> type(x)
<class 'str'>

这解释了为什么Python被称为动态类型语言。

以下Python内置数据类型也可以在Jython中使用 -

  • Number
  • String
  • List
  • Tuple
  • Dictionary

Python将数字数据识别为数字,可以是整数,带浮点的实数或复数。 String,List和Tuple数据类型称为序列。

Jython数字

在Python中,任何带符号的整数都被称为'int'类型。 为了表示一个长整数,附加字母'L'。 将整数部分与小数部分分开的小数点数字称为“浮点数”。 小数部分可以包含使用'E'或'e'以科学记数法表示的指数。

复数也在Python中定义为数值数据类型。 复数包含实部(浮点数)和附加有'j'的虚部。

为了表示八进制或十六进制表示中的数字,将0O0X作为前缀。 以下代码块给出了Python中不同数字表示的示例。

int     -> 10, 100, -786, 80
long    -> 51924361L, -0112L, 47329487234L
float   -> 15.2, -21.9, 32.3+e18, -3.25E+101
complex -> 3.14j, 45.j, 3e+26J, 9.322e-36j

Jython Strings

字符串是用单个(例如“hello”),double(例如“hello”)或三个(例如“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-printable
characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs
within the string, whether explicitly given like this within the brackets [ \n ], or just
a NEWLINE within the variable assignment will also show up.
"""

打印时的第三个字符串将给出以下输出。

this is a long string that is made up of
several lines and non-printable characters such as
TAB ( 	 ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.

Jython列表

List是序列数据类型。 它是逗号分隔项的集合,不一定是同一类型,存储在方括号中。 可以使用基于零的索引访问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表达 描述
len(List)Length
List[2]=10Updation
Del List [1] Deletion
List.append(20)Append
List.insert(1,15)Insertion
List.sort()Sorting

Jython Tuples

元组是存储在括号中的逗号分隔数据项的不可变集合。 无法删除或修改元组中的元素,也无法将元素添加到元组集合中。 以下代码块显示了Tuple操作。

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字典

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表达 描述
dict.get(‘011’)Search
len(dict)Length
dict ['044'] ='钦奈' Append
del dict ['022'] Delete
dict.keys()list of keys
dict.values()List of values
dict.clear() 删除所有元素
↑回到顶部↑
WIKI教程 @2018