Jython - 变量和数据类型


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

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


> 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'。用小数点分隔整数部分和小数分量的数字称为 'float'。小数部分可能包含以科学记数法表示的指数,使用“E”或“e”表示。

在 Python 中,复数也被定义为数字数据类型。复数包含一个实部(浮点数)和一个附加了 'j' 的虚部。

为了以八进制或十六进制表示形式表示数字,其前缀为 0O 或 0X。以下代码块提供了 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 字符串

字符串是用单引号(例如“你好”)、双引号(例如“你好”)或三引号(例如“你好”)或“”你好“”)引号括起来的任何字符序列。如果字符串的内容跨越多行,则三引号特别有用。

转义序列字符可以逐字包含在三引号字符串中。以下示例显示了在 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) 长度
List[2]=10 更新
Del List[1] 删除
List.append(20) 附加
List.insert(1,15) 插入
List.sort() 排序

Jython 元组

元组是存储在括号中的逗号分隔数据项的不可变集合。无法删除或修改 Tuples 中的元素,也无法将元素添加到 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 对象中多次出现。但是,多个键可以具有相同的关联值。下面解释了 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’) 搜索
len(dict) 长度
dict[‘044’] = ‘Chennai’ 附加
del dict[‘022’] 删除
dict.keys() 键列表
dict.values() 值列表
dict.clear() 删除所有元素