pythontuples_python - tuples

tuples

tuples are like lists, they have elements which are indexed starting at 0

x = ('ke','is','sleepy')

print(x[2])

y = (1,2,3)

print(y[0])

print(max(y))

Why tuples (an immutable list)?

The immutable list provides a data structure with some integrity and some persistence. It is not possible to accidentally change a tuple.

tuples are immutable!!

things not to do with tuples:

x = (1,2,3)

x.sort()

x.append()

x.reverse()

# 与list比较可以用的函数

l = list()

t = tuple()

dir(l)

dir(t) # count , index

tuples are more efficient

tuples and assignment

we can also put a tuple on the left-hand side of an assignment statement

(x,y) = (1, 'ke')

print(y)

(a,b) = (22,33)

print(a)

tuples and dictionaries

d = dict()

d['1'] = 1

d['2'] = 2

for (k,v) in d.items():

print(k,v)

tups = d.items()

print(tups)

tuples are comparable

if the first item is equal, go to the second item to compare until it finds the element that differs. 只要比较了一个了,后面的就不需要比较

sorting lists of tuples

first, we sort the dictionary by the key using the items() method and sorted() function.

d = {'a':22, 'h':11, 'f':22}

d.items()

sorted(d.items(),reverse = True)

it's also possible to sort by values instead of key: construct a list of tuples of the form (value, key) we could sort by value.

sort a tuple by sorted method, then it returns a list. So we need to convert it back to a tuple.

sorted_list = sorted(a_tuple)

new_tuple = tuple(sorted_list)

top10 most common

d = {'a':22, 'h':11, 'f':22}

print(sorted([(v,k) for k,v in d.items()]))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值