Python中的元组究竟是什么?

5 python tuples list

我正在进行几次Pythone练习,我很难接受这个练习.

# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
  # +++your code here+++
  return
Run Code Online (Sandbox Code Playgroud)

什么是元组?它们是指列表清单吗?

AKX*_*AKX 14

元组是Python中最简单的序列类型.您可以将其视为不可变(只读)列表:

>>> t = (1, 2, 3)
>>> print t[0]
1
>>> t[0] = 2
TypeError: tuple object does not support item assignment
Run Code Online (Sandbox Code Playgroud)

只需将元组传递给list()(就像任何可迭代的一样),可以将元组转换为新的列表,并且可以将任何可迭代的元组转换为新的元组tuple():

>>> list(t)
[1, 2, 3]
>>> tuple(["hello", []])
("hello", [])
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.另请参阅本教程关于元组的内容.


小智 3

元组和列表非常相似。主要区别(作为用户)是元组是不可变的(无法修改)

在你的例子中:

[(2, 2), (1, 3), (3, 4, 5), (1, 7)]
Run Code Online (Sandbox Code Playgroud)

这是一个元组列表 [...] 列表 (2,2) 是一个元组