python学习日记(一)

来源:互联网 发布:php 在线考试 编辑:程序博客网 时间:2024/05/24 16:14

list

len长度

list在Python中是一种数据集,类似于php中的数组,list在php中是一个函数,是list($a,$b) = array(1,2);

python中list的insert(i,data)方法是插入元素, 

>>> classmates = ['one','two','three']
>>> classmates
['one', 'two', 'three']

>>> classmates.insert(-1,'four')
>>> classmates
['one', 'two', 'four', 'three']

插入-1位置,是插入最后一个之前的位置

append(data)是在末尾追加元素

删除是pop(i)


tuple

tuple区别于list,定义之后不可变,定义一个tuple是用圆括号(),区别于list的方括号[],tuple内可嵌入list,某个元素为list,这个元素就可变

tuple和list可以彼此嵌套

>>> classmates = [1,2,3,(1,2,3)]
>>> classmates
[1, 2, 3, (1, 2, 3)]
>>> classmates[2] = 4
>>> classmates
[1, 2, 4, (1, 2, 3)]
>>> classmates[3][1]
2
>>> classmates[3][1] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> classmates1 = (1,2,3,['a','b'])
>>> classmates1
(1, 2, 3, ['a', 'b'])

>>> classmates1[3][0] = 'c'
>>> classmates1
(1, 2, 3, ['c', 'b'])


list 只有数字索引,没有字符串索引

classmates['a'] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str


条件判断

和其他语言类似

循环

和其他语言类似

range()函数,可以生成一个整数序列



dict区别于list,使用key-value存储数据,定义使用大括号{key:value}

set区别于dictset和dict的唯一区别仅在于没有存储对应的value

定义 s=set([1,2,3]),set不能重复,也不表示有序


函数

内置函数直接调用

定义函数 def fname():

空函数可以用 pass 跳过

函数返回的结果为tuple,所以返回结果不能修改

>>> def fname():
...     return 1,2
...
>>> fname()
(1, 2)
>>> x = fname()
>>> x
(1, 2)
>>> x[0] = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

函数调用














原创粉丝点击