Jython 变量和数据类型

Jython 变量和数据类型

变量是计算机内存中命名的位置。每个变量可以容纳一条数据。与Java不同,Python是一种动态类型语言。因此,在使用Jython时也不需要事先声明变量的数据类型。变量的类型取决于其所存储的数据类型,而不是变量本身的类型。

在下面的示例中,一个变量被赋予一个整数值。通过使用内置的type()函数,我们可以验证变量的类型是整数。但是,如果将同一个变量赋值为一个字符串,type()函数将返回字符串作为该变量的类型。

> x = 10
>>> type(x)
<class 'int'>

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

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

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

  • 数字
  • 字符串
  • 列表
  • 元组
  • 字典

Python将数值数据识别为数字,可以是整数、带有浮点数的实数或复数。字符串、列表和元组数据类型被称为序列。

Jython数字

在Python中,任何带符号的整数被称为’int’类型。要表示长整数,需要在其后加上字母 ‘L’。有小数点将整数部分和小数部分分开的数被称为’float’类型。小数部分可能包含使用科学计数法使用’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字符串

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

转义字符可以直接包含在三引号字符串中。以下示例展示了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 列表

列表是一种序列数据类型。它是一组逗号分隔的项的集合,不一定是相同类型的,存储在方括号中。可以使用基于零的索引来访问列表中的各个项。

以下代码块总结了在 Python 中使用列表的用法。

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 Lists相关的一些常见的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 字典

Jython 字典类似于 Java Collection 框架中的 Map 类。它是一组键值对。用逗号分隔的键值对被括在花括号中。字典对象不按零索引来检索其中的元素,因为它们是通过哈希技术存储的。

在字典对象中,同一个键不能出现多次。然而,多个键可以具有相同的关联值。下面解释了字典对象的不同函数:

dict = {'011':'New Delhi','022':'Mumbai','033':'Kolkata'}
print "dict[‘011’]: ",dict['011']
print "dict['Age']: ", dict['Age']

下表描述了与字典相关的一些常见的Jython表达式。

Jython Expression Description
dict.get(‘011’) Search
len(dict) Length
dict[‘044’] = ‘Chennai’ Append
del dict[‘022’] Delete
dict.keys() list of keys
dict.values() List of values
dict.clear() Removes all elements

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程