python学习日记[2]

本文深入探讨了Python中元组与列表的特性对比,详细介绍了元组的不可变性以及列表的灵活性,并通过实例展示了元组在序列、函数、字符串格式化等方面的应用,特别强调了元组在函数参数传递、闭包和多参数调用时的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

元组:(用())

和列表的不同:

1、 列表更加灵活,可以任意的添加删除元素,元组一旦被创建就不可更改;

 

>>> dir(test)

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

>>> test[1:]

(2, 3, 4)

>>> test[:3]

(1, 2, 3)

>>> test[1:]

(2, 3, 4)

>>> test[:3]

(1, 2, 3)

  

p.s.

1、 在列表和元素中元素的类型不做限定,可以嵌套,有点类似于锯齿数组

2、 切片

格式化操作string:

1、 类似于C语言中printf一类函数要求的格式化输入。

2、 格式控制符的转义。

序列:

1、list() -> new empty list

list(iterable) -> new list initialized from iterable's items

2、 zip()---zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。

函数:

定义 def return_value function_name(parameters):

#函数实现

1、 函数嵌套---Python支持函数内嵌—函数内部定义函数;

2、 函数闭包---子函数可以使用父函数中的局部变量,这种行为就叫做闭包!

clip_image004

示例图解

3、拓展阅读

>>> def test1(*aaa):
	print(aaa)
	def test2():
		print(aaa)

		
>>> test1(1,2,3,4)
(1, 2, 3, 4)
>>> def test1(*aaa):
	print(aaa)
	def test2():
		print(aaa)
		print('test2_function called')

		
>>> test1(1,23,4)
(1, 23, 4)
>>> test2()

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    test2()
NameError: name 'test2' is not defined
>>> def test1(*aaa):
	print(aaa)
	def test2():
		print(aaa)
		print('test2_function called')
		return aaa*2
	return test2()

>>> test1(1,2,3)
(1, 2, 3)
(1, 2, 3)
test2_function called
(1, 2, 3, 1, 2, 3)

  

转载于:https://www.cnblogs.com/jokervwer/p/4247857.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值