元组-----Python

元组:

元组是一种序列,就像列表一样。元组和列表之间的区别在于,与列表(可变)不同,元组不能更改(不可变)。 元组使用括号,而列表使用方括号。

优点:运行时间快!

初始化一个元组 

空元组:emptyTuple = ()

多元组:

# way 1

z = (3, 7, 4, 2)

# way 2 (tuples can also can be created without parenthesis)

z = 3, 7, 4, 2

单元组:

重要的是要记住,如果要创建仅包含一个值的元组,则需要在项目后面添加一个逗号。

# tuple with one value

tup1 = ('Michael',)

# tuple with one value

tup2 = 'Michael', 

# This is a string, NOT a tuple.

notTuple = ('Michael')

访问元组内的值 :与列表雷同

# Initialize a tuple
z = (3, 7, 4, 2)

# Access the first item of a tuple at index 0
print(z[0])
print(z[-1])



#输出:
3
2

切分元组 :与列表雷同

# Initialize a tuple
z = (3, 7, 4, 2)

# first index is inclusive (before the :) and last (after the :) is not.
print(z[0:2])
print(z[:3])
print(z[-4:-1])


#输出:
(3, 7)
(3, 7, 4)
(3, 7, 4)

即使元组是不可变的,也可以采用现有元组的一部分来创建新的元组,如下例所示。 

# Initialize tuple
tup1 = ('Python', 'SQL')

# Initialize another Tuple
tup2 = ('R',)

# Create new tuple based on existing tuples
new_tuple = tup1 + tup2;
print(new_tuple)


#输出:
('Python', 'SQL', 'R')

 元组内部索引和元组数计数

 

# Initialize a tuple
animals = ('lama', 'sheep', 'lama', 48)

print(animals.index('lama'))
print(animals.count('lama'))


#输出:
0
2

遍历: 

for item in animals:

for item in animals:
    print(item)


#输出:
lama
sheep
lama
48

元组拆包 :数字序列

x, y = (7, 10);
print("Value of x is {}, the value of y is {}.".format(x, y))


#输出:
Value of x is 7, the value of y is 10.

 枚举(enumerate):

friends = ('Steve', 'Rachel', 'Michael', 'Monica')
for index, frien in enumerate(friends):
    print(index,frien)


#输出:
0 Steve
1 Rachel
2 Michael
3 Monica

元组可以用作字典键 

而列表不可以作为字典键

 

bigramsTupleDict = {('this', 'is'): 23,
                    ('is', 'a'): 12,
                    ('a', 'sentence'): 2}

print(bigramsTupleDict)


#输出:
{('is', 'a'): 12, ('this', 'is'): 23, ('a', 'sentence'): 2}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

静海彭于晏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值