python基础之元组,列表

简介: >>> menber=["小甲鱼","不定","怡欣","mt"]>>> for each in menber: print(each,len(each))python的内置对象预览:Number(数字):3.

>>> menber=["小甲鱼","不定","怡欣","mt"]

>>> for each in menber:
	print(each,len(each))

python的内置对象预览:

Number(数字):3.0145,1234,99L,3+4j(负数常量)

String(字符串):'sapm',"红色经'kkk'典"

List(列表):[1,[2,'three points'],4]

Dictionary(字典):{'food':'spam','taste':'yum'}

Tuple(元组):(1,'spam',4,'U')

File(文件):text=open{'segg','r'}.read()


python的比较操作符与java一样

> 大于

< 小于

------------------------------------------------------------

条件分支语法:

①if 条件:

→缩进   条件为真执行

else:

→缩进条件为假执行操作

②while

while 条件:

条件为真执行操作


and逻辑操作运算符


随机:random模块

randint(),会返回一个随机整数




类型转换

整数→字符串str()例如str(132412)变为'132412'

整数→浮点型float()

int()注意:浮点数转换为整数时会采取截断处理。



获取类型信息

type()返回类型

例子:a='reui'

type(a)


isinstance()方法 

例子:isistance('eq',str)

返回一个布尔类型值。是否是这个类型


循环:

while  循环:

while 条件:、

循环体

for循环:

for   目标  in  表达式列表:

循环体


range() 

语法:range() ([strat,] stop[,step=1])

step=1,默认的值为1;range作用是生产一个从start参数的值开始到stop参数的数字序列



列表:

因为python中变量没有类型,而数组元素的类型是相等的,所以python没有数组,所以列表是加强版的数组~

①创建普通列表

例如:数组名=[1,23,3,4,4,4,4]

②混合列表(列表的成员变量类型包括很多类型)

③创建空列表:empty=[]


对列表的操作:

显示长度→len(列表名)

向列表中添加元素→列表名.append(变量)   

        向列表中插入列表→列表名.extend([变量1,变量2 ,] )

插入列表中任意位置→列表名.insert(2,"ds")  插入第二个位置


删除列表元素→remove("成员变量")   

del  menber[4]→删除第五个成员

       返回并删除该值→pop(5)   删除第6个元素

列表的分片slice

 menber[1:3]   :将会显示第二个和第三个成员变量,形成了对源列表的拷贝!


列表的比较操作符:

>>> list1=[123,345]
>>> list2=[234,123]
>>> list1>list2
False
只要列表1的第一个元素大于列表2,那么,后面的数就不用比较了。

+号运算

>>> list1+"xiaojiayu"
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    list1+"xiaojiayu"
TypeError: can only concatenate list (not "str") to list
>>> list1+list2
[123, 345, 234, 123]
>>> 
*号运算

>>> list1*3
[123, 345, 123, 345, 123, 345]


in运算符  只能够影响一层

>>> list5=[123,["xiaojiayu","why"]]
>>> list4=[123,"xiaojiayu","why"]
>>> "why" in list4
True
>>> "why" in list5
False
>>> 

查看list的内置函数:

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> 
使用:

count 计数

>>> list4.count(123)
1

转置reverse()

排序sort(0):默认是从小到大排序

>>> list6=[1,0,9,5,4,7,6,2,11,10]
>>> list6.sort()
>>> list6
[0, 1, 2, 4, 5, 6, 7, 9, 10, 11]
>>> list6.reverse()
>>> list6
[11, 10, 9, 7, 6, 5, 4, 2, 1, 0]
>>> 
或者

>>> list6.sort(reverse=True)
>>> list6
[11, 10, 9, 7, 6, 5, 4, 2, 1, 0]
>>> 

列表的复制:

>>> list7=list6[2:9]
>>> list7
[9, 7, 6, 5, 4, 2, 1]
如果是用=号时,就是给这个列表起了另一个名字,而分片儿复制则会在内存中实实在在的分配存储空间。




元组:戴上了加锁的列表(不能随意插入,删除等操作)

>>> tuple1=(1,2,3,5,8,6,9)
>>> tuple1
(1, 2, 3, 5, 8, 6, 9)
>>> tuple1[3]
5
>>> tuple1[1:3]
(2, 3)
>>> temp=(1)
>>> type(temp)
<class 'int'>
>>> type(temp1=(1,))
TypeError: type() takes 1 or 3 arguments
>>> temp=(1,)
>>> type(temp)
<class 'tuple'>
>>> 


插入操作:(生成新的元组)

>>> temp=("意境","和","下架与")
>>> temp=temp[:2]+("哇")+temp[2:]
Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    temp=temp[:2]+("哇")+temp[2:]
TypeError: can only concatenate tuple (not "str") to tuple
>>> temp=temp[:2]+("哇",)+temp[2:]
>>> temp
('意境', '和', '哇', '下架与')
>>> 



字符串之内置方法

>>> str='i am fool ,yami'
>>> str
'i am fool ,yami'
>>> find("fool")
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    find("fool")
NameError: name 'find' is not defined
>>> find('fool')
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    find('fool')
NameError: name 'find' is not defined
>>> str.find('fool')
5
>>> str.join('123')
'1i am fool ,yami2i am fool ,yami3'
>>> "{a} love {b} {c}".format("i" ,"want" ,"to do")
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    "{a} love {b} {c}".format("i" ,"want" ,"to do")
KeyError: 'a'
>>> "{a} love {b} {c}".format(a="i" ,b="want" ,c="to do")
'i love want to do'
>>> "{1} love {2} {3}".format("i" ,"want" ,"to do")
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    "{1} love {2} {3}".format("i" ,"want" ,"to do")
IndexError: tuple index out of range
>>> "{0} love {1} {2}".format("i" ,"want" ,"to do")
'i love want to do'
>>> 

序列:

列表,数组和字符串的共同点

可以通过索引得到每个元素

索引默认为从0开始

可以通过分片的方法得到一个范围内的元素的集合

共同操作符


list()将一个可迭代对象转换为列表

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

>> help(list)
Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.n
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |  
 |  __rmul__(self, value, /)
 |      Return self*value.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None



相关文章
|
3天前
|
索引 容器
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
|
4天前
|
存储 索引 Python
python学习7-元组
python学习7-元组
|
4天前
|
存储 索引 Python
python学习5-列表的创建、增删改查、排序
python学习5-列表的创建、增删改查、排序
|
7天前
|
存储 安全 索引
「Python系列」Python元组
Python中的元组(Tuple)是一种不可变的有序序列类型,它允许你存储多个不同类型的元素,并且这些元素在元组中是按照特定的顺序排列的。一旦一个元组被创建,你就不能修改它(即不能添加、删除或更改元组中的元素),这使得元组成为一种非常安全的数据结构,因为一旦它们被创建,就不
15 1
|
9天前
|
索引 Python 容器
python 数据类型之列表
python 数据类型之列表
|
17天前
|
存储 Java 程序员
【Python】6. 基础语法(4) -- 列表+元组+字典篇
【Python】6. 基础语法(4) -- 列表+元组+字典篇
40 1
|
22天前
|
程序员 C语言 Python
Python列表推导式:简洁与高效的编程利器
在Python编程中,列表推导式(List Comprehension)是一种强大且优雅的工具,它允许我们以简洁的方式创建新的列表。列表推导式在Python程序员中广受欢迎,因为它能够将复杂的循环和条件语句简化为一行代码,提高代码的可读性和执行效率。
|
28天前
|
Python
python列表问题
python列表问题
|
28天前
|
存储 前端开发 C++
【Python 基础教程 09】全面掌握Python3列表:从入门到精通的综合教程与实战指南
【Python 基础教程 09】全面掌握Python3列表:从入门到精通的综合教程与实战指南
88 1
|
1月前
|
Python
python操作列表方法(三)
python操作列表方法(三)
21 2

热门文章

最新文章