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



相关文章
|
1月前
|
缓存 监控 数据可视化
微店item_search - 根据关键词取商品列表深度分析及 Python 实现
微店item_search接口可根据关键词搜索商品,返回商品信息、价格、销量等数据,适用于电商检索、竞品分析及市场调研。接口需通过appkey与access_token认证,支持分页与排序功能,Python示例代码实现调用流程,助力商品数据高效获取与分析。
|
9天前
|
开发者 Python
Python神技:用列表推导式让你的代码更优雅
Python神技:用列表推导式让你的代码更优雅
231 99
|
16天前
|
程序员 Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
217 99
|
14天前
|
缓存 算法 数据安全/隐私保护
VVICitem_search - 根据关键词取关键词取商品列表接口深度分析及 Python 实现
VVIC item_search接口支持关键词搜索服装商品,提供价格、销量、供应商等数据,助力市场调研与采购决策。
|
17天前
|
自然语言处理 算法 数据安全/隐私保护
item_review - Lazada 商品评论列表接口深度分析及 Python 实现
Lazada商品评论接口(item_review)可获取东南亚多国用户评分、评论内容、购买属性等数据,助力卖家分析消费者偏好、优化产品与营销策略。
|
3月前
|
索引 Python 容器
[oeasy]python096_列表_计数函数_count
本教程详细介绍了Python中列表的计数方法`count`,包括其基本用法、与`len`函数的区别,以及如何结合索引操作查找和删除特定元素。同时探讨了字符串对象的`count`方法,并通过实例演示了如何统计字符出现次数。
71 7
|
2月前
|
安全 测试技术 数据处理
Python列表推导式进阶:从简洁代码到高效编程的10个核心技巧
列表推导式是Python中高效的数据处理工具,能将多行循环代码压缩为一行,提升代码可读性与执行效率。本文详解其基础语法、嵌套循环、条件表达式、函数融合、性能优化等进阶技巧,并结合实战案例与边界条件处理,帮助开发者写出更优雅、高效的Python代码。
123 0
|
2月前
|
存储 程序员 数据处理
Python列表基础操作全解析:从创建到灵活应用
本文深入浅出地讲解了Python列表的各类操作,从创建、增删改查到遍历与性能优化,内容详实且贴近实战,适合初学者快速掌握这一核心数据结构。
186 0
|
3月前
|
JSON 数据挖掘 API
闲鱼商品列表API响应数据python解析
闲鱼商品列表API(Goodfish.item_list)提供标准化数据接口,支持GET请求,返回商品标题、价格、图片、卖家信息等。适用于电商比价、数据分析,支持多语言调用,附Python示例代码,便于开发者快速集成。
|
3月前
|
JSON API 数据格式
微店商品列表API响应数据python解析
微店商品列表API为开发者提供稳定高效获取商品信息的途径,支持HTTP GET/POST请求,返回JSON格式数据,含商品ID、名称、价格、库存等字段,适用于电商数据分析与展示平台搭建等场景。本文提供Python调用示例,助您快速上手。

推荐镜像

更多