Python🐍

python - tuples

2020-09-03  本文已影响0人  Pingouin

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!!

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

(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

sorting lists of tuples

  1. 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.

  1. 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()]))
上一篇 下一篇

猜你喜欢

热点阅读