Python列表(List)的常用操作示例/数字列表/基本操作/Python3.10

本文详细介绍Python列表的基本操作,包括列表的创建、索引访问、元素修改、添加与删除、排序及切片等实用技巧。此外,还介绍了数字列表的操作方法。

Python列表的常用操作

1、列表的创建

animals=['dog','cat','lion','rat',2022]
#也可以是:
animals=list['dog','cat','lion','rat',2022]
# 空列表
lst=list()
lst=[]

2、列表的索引

访问元素,下标取值范围:[0,n-1]并上[-n,-1],0到n-1是第一个元素开始往后数,-1到-n是最后一个开始元素往前数:

print('最后一个元素是:',animals[-1])
print('第一个元素是:',animals[0])
print('按值查找下标:',animals.index(2022))

结果:

最后一个元素是: 2022
第一个元素是: dog
按值查找下标: 4

3、列表的修改元素:

print('修改前:',animals)
animals[3]='mouse'
print('修改索引为3的元素后:',animals)

结果:

修改前: ['dog', 'cat', 'lion', 'rat', 2022]
修改索引为3的元素后: ['dog', 'cat', 'lion', 'mouse', 2022]

4、列表的添加元素:

animals.append('bird')#在末尾添加元素
animals.insert(3,'panda')#在索引为3的位置插入元素
print('添加元素后:',animals)

结果:

添加元素后: ['dog', 'cat', 'lion', 'panda', 'mouse', 2022, 'bird']

5、列表的删除元素:

del语句:

del animals[0]
print('删除了列表索引为0的元素后:',animals)

结果:

删除了列表索引为0的元素后: ['cat', 'lion', 'panda', 'mouse', 2022, 'bird']

pop()方法:

pop()方法用于弹出列表末尾的元素,并可以被接收,在括号内加索引也可以弹出任意位置的元素

poped_animal=animals.pop()
print('弹出了末尾的元素后:',animals)
print('被弹出的元素',poped_animal)

结果:

弹出了末尾的元素后: ['cat', 'lion', 'panda', 'mouse', 2022]
被弹出的元素 bird

按值删除的remove()方法:

animals.remove(2022)
print('移除后:',animals)

结果:

移除后: ['cat', 'lion', 'panda', 'mouse']

6、列表的排序:

animals.sort()
print('按照字母顺序排序后:',animals)
animals.sort(reverse=True)
print('按照字母顺序反向排序后:',animals)
print('用sorted()临时排序:',sorted(animals))
print(animals)

结果:

按照字母顺序排序后: ['cat', 'lion', 'mouse', 'panda']
按照字母顺序反向排序后: ['panda', 'mouse', 'lion', 'cat']sorted()临时排序: ['cat', 'lion', 'mouse', 'panda']
['panda', 'mouse', 'lion', 'cat']

7、列表的切片:

print('切片前:',animals)
print('[开始下标:结束下标:步长]:',animals[1:3:1])

结果:

切片前: ['panda', 'mouse', 'lion', 'cat']
[开始下标:结束下标:步长]['mouse', 'lion']

8、数字列表的一些操作:

numbers=list(range(0,24,3))
print(numbers)
print('最大值:',max(numbers))
print('最小值:',min(numbers))
print('求和:',sum(numbers))

结果:

[0, 3, 6, 9, 12, 15, 18, 21]
最大值: 21
最小值: 0
求和: 84
读取原始文件... 变量列表: [&#39;tasu&#39;, &#39;lat&#39;, &#39;lon&#39;, &#39;time&#39;, &#39;time_bnds&#39;, &#39;lat_bnds&#39;, &#39;lon_bnds&#39;] 时间单位: days since 2015-01-01 00:00:00 日历类型: 365_day tasu变量形状: (1032, 192, 288) tasu单位: K 时间范围: 2015-02-01 00:00:00 到 2101-01-01 00:00:00 索引 0: 2015-02-01 00:00:00 索引 1: 2015-03-01 00:00:00 索引 2: 2015-04-01 00:00:00 索引 3: 2015-05-01 00:00:00 索引 4: 2015-06-01 00:00:00 索引 5: 2015-07-01 00:00:00 索引 6: 2015-08-01 00:00:00 索引 7: 2015-09-01 00:00:00 索引 8: 2015-10-01 00:00:00 索引 9: 2015-11-01 00:00:00 索引 10: 2015-12-01 00:00:00 索引 11: 2016-01-01 00:00:00 找到 12 个目标时间点 /Users/apple/Desktop/Python/#tas.py:70: UserWarning: WARNING: missing_value not used since it cannot be safely cast to variable data type tasu_data = tasu_var[target_indices, :, :] 创建新文件... /Users/apple/Desktop/Python/#tas.py:119: UserWarning: WARNING: missing_value cannot be safely cast to variable dtype setattr(tasu_out, attr, getattr(tasu_var, attr)) 数据提取完成,保存为: /Users/apple/Desktop/tas/urban_temperature_2015-201601.nc /Users/apple/Desktop/Python/#tas.py:136: UserWarning: WARNING: missing_value not used since it cannot be safely cast to variable data type tasu = ds.variables[&#39;tasu&#39;][time_index, :, :] # 选择指定时间 /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/cartopy/io/__init__.py:241: DownloadWarning: Downloading: https://naturalearth.s3.amazonaws.com/50m_physical/ne_50m_ocean.zip warnings.warn(f&#39;Downloading: {url}&#39;, DownloadWarning) 处理过程中出现错误: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 1348, in do_open h.request(req.get_method(), req.selector, req.data, headers, File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py", line 1282, in request self._send_request(method, url, body, headers, encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py", line 1328, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py", line 1277, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py", line 1037, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py", line 975, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py", line 1454, in connect self.sock = self._context.wrap_socket(self.sock, File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/ssl.py", line 512, in wrap_socket return self.sslsocket_class._create( File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/ssl.py", line 1070, in _create self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/ssl.py", line 1341, in do_handshake self._sslobj.do_handshake() ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/apple/Desktop/Python/#tas.py", line 254, in main plot_temperature_map(output_file, time_idx, month_name) File "/Users/apple/Desktop/Python/#tas.py", line 194, in plot_temperature_map plt.savefig(output_png, dpi=300, bbox_inches=&#39;tight&#39;) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/pyplot.py", line 958, in savefig res = fig.savefig(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/figure.py", line 3019, in savefig self.canvas.print_figure(fname, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/backend_bases.py", line 2295, in print_figure self.figure.draw(renderer) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/artist.py", line 73, in draw_wrapper result = draw(artist, renderer, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/artist.py", line 50, in draw_wrapper return draw(artist, renderer) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/figure.py", line 2810, in draw mimage._draw_list_compositing_images( File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/image.py", line 132, in _draw_list_compositing_images a.draw(renderer) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/artist.py", line 50, in draw_wrapper return draw(artist, renderer) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/cartopy/mpl/geoaxes.py", line 538, in draw return super().draw(renderer=renderer, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/artist.py", line 50, in draw_wrapper return draw(artist, renderer) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 3082, in draw mimage._draw_list_compositing_images( File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/image.py", line 132, in _draw_list_compositing_images a.draw(renderer) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/artist.py", line 50, in draw_wrapper return draw(artist, renderer) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/cartopy/mpl/feature_artist.py", line 151, in draw geoms = self._feature.intersecting_geometries(extent) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/cartopy/feature/__init__.py", line 303, in intersecting_geometries return super().intersecting_geometries(extent) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/cartopy/feature/__init__.py", line 106, in intersecting_geometries return (geom for geom in self.geometries() if File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/cartopy/feature/__init__.py", line 285, in geometries path = shapereader.natural_earth(resolution=self.scale, File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/cartopy/io/shapereader.py", line 283, in natural_earth return ne_downloader.path(format_dict) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/cartopy/io/__init__.py", line 203, in path result_path = self.acquire_resource(target_path, format_dict) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/cartopy/io/shapereader.py", line 337, in acquire_resource shapefile_online = self._urlopen(url) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/cartopy/io/__init__.py", line 242, in _urlopen return urlopen(url) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 216, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 519, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 536, in _open result = self._call_chain(self.handle_open, protocol, protocol + File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 496, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 1391, in https_open return self.do_open(http.client.HTTPSConnection, req, File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 1351, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)>
10-17
修改后的新代码遇到报错: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/lib/utils.py", line 523, in open_for_read return open_for_read_by_name(name,mode) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/lib/utils.py", line 463, in open_for_read_by_name return open(name,mode) FileNotFoundError: [Errno 2] No such file or directory: &#39;SimSun.ttf&#39; During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/lib/utils.py", line 530, in open_for_read return BytesIO((datareader if name[:5].lower()==&#39;data:&#39; else rlUrlRead)(name)) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/lib/utils.py", line 476, in rlUrlRead return urlopen(name).read() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 216, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 503, in open req = Request(fullurl, data) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 322, in __init__ self.full_url = url File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 348, in full_url self._parse() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 377, in _parse raise ValueError("unknown url type: %r" % self.full_url) ValueError: unknown url type: &#39;SimSun.ttf&#39; During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/pdfbase/ttfonts.py", line 159, in TTFOpenFile f = open_for_read(fn,&#39;rb&#39;) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/lib/utils.py", line 534, in open_for_read return open_for_read(name,mode) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/lib/utils.py", line 532, in open_for_read raise IOError(&#39;Cannot open resource "%s"&#39; % name) OSError: Cannot open resource "SimSun.ttf" During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/bravesword/Desktop/legal soup/test1.py", line 164, in <module> save_text_to_pdf(extracted_text, output_pdf) File "/Users/bravesword/Desktop/legal soup/test1.py", line 117, in save_text_to_pdf pdfmetrics.registerFont(TTFont(&#39;SimSun&#39;, &#39;SimSun.ttf&#39;)) # 确保字体文件路径正确 File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/pdfbase/ttfonts.py", line 1207, in __init__ self.face = TTFontFace(filename, validate=validate, subfontIndex=subfontIndex) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/pdfbase/ttfonts.py", line 1088, in __init__ TTFontFile.__init__(self, filename, validate=validate, subfontIndex=subfontIndex) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/pdfbase/ttfonts.py", line 447, in __init__ TTFontParser.__init__(self, file, validate=validate,subfontIndex=subfontIndex) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/pdfbase/ttfonts.py", line 183, in __init__ self.readFile(file) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/pdfbase/ttfonts.py", line 259, in readFile self.filename, f = TTFOpenFile(f) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/reportlab/pdfbase/ttfonts.py", line 169, in TTFOpenFile raise TTFError(&#39;Can\&#39;t open file "%s"&#39; % fn) reportlab.pdfbase.ttfonts.TTFError: Can&#39;t open file "SimSun.ttf"
08-03
(superset) superset@VM-0-6-ubuntu:~$ superset db upgrade 2025-11-25 17:33:24,093:INFO:superset.utils.screenshots:No PIL installation found 2025-11-25 17:33:24,432:ERROR:superset.app:Failed to create app Traceback (most recent call last): File "/opt/superset/lib/python3.10/site-packages/superset/app.py", line 40, in create_app app_initializer.init_app() File "/opt/superset/lib/python3.10/site-packages/superset/initialization/__init__.py", line 479, in init_app self.init_app_in_ctx() File "/opt/superset/lib/python3.10/site-packages/superset/initialization/__init__.py", line 417, in init_app_in_ctx self.init_views() File "/opt/superset/lib/python3.10/site-packages/superset/initialization/__init__.py", line 130, in init_views from superset.cachekeys.api import CacheRestApi File "/opt/superset/lib/python3.10/site-packages/superset/cachekeys/api.py", line 27, in <module> from superset.cachekeys.schemas import CacheInvalidationRequestSchema File "/opt/superset/lib/python3.10/site-packages/superset/cachekeys/schemas.py", line 20, in <module> from superset.charts.schemas import ( File "/opt/superset/lib/python3.10/site-packages/superset/charts/schemas.py", line 427, in <module> class ChartDataAggregateOptionsSchema(ChartDataPostProcessingOperationOptionsSchema): File "/opt/superset/lib/python3.10/site-packages/superset/charts/schemas.py", line 433, in ChartDataAggregateOptionsSchema fields.List( File "/opt/superset/lib/python3.10/site-packages/marshmallow/fields.py", line 711, in __init__ super().__init__(**kwargs) TypeError: Field.__init__() got an unexpected keyword argument &#39;minLength&#39; Traceback (most recent call last): File "/opt/superset/bin/superset", line 7, in <module> sys.exit(superset()) File "/opt/superset/lib/python3.10/site-packages/click/core.py", line 1485, in __call__ return self.main(*args, **kwargs) File "/opt/superset/lib/python3.10/site-packages/click/core.py", line 1406, in main rv = self.invoke(ctx) File "/opt/superset/lib/python3.10/site-packages/click/core.py", line 1870, in invoke super().invoke(ctx) File "/opt/superset/lib/python3.10/site-packages/click/core.py", line 1269, in invoke return ctx.invoke(self.callback, **ctx.params) File "/opt/superset/lib/python3.10/site-packages/click/core.py", line 824, in invoke return callback(*args, **kwargs) File "/opt/superset/lib/python3.10/site-packages/click/decorators.py", line 34, in new_func return f(get_current_context(), *args, **kwargs) File "/opt/superset/lib/python3.10/site-packages/flask/cli.py", line 355, in decorator app = __ctx.ensure_object(ScriptInfo).load_app() File "/opt/superset/lib/python3.10/site-packages/flask/cli.py", line 309, in load_app app = locate_app(import_name, name) File "/opt/superset/lib/python3.10/site-packages/flask/cli.py", line 236, in locate_app return find_best_app(module) File "/opt/superset/lib/python3.10/site-packages/flask/cli.py", line 64, in find_best_app app = app_factory() File "/opt/superset/lib/python3.10/site-packages/superset/app.py", line 40, in create_app app_initializer.init_app() File "/opt/superset/lib/python3.10/site-packages/superset/initialization/__init__.py", line 479, in init_app self.init_app_in_ctx() File "/opt/superset/lib/python3.10/site-packages/superset/initialization/__init__.py", line 417, in init_app_in_ctx self.init_views() File "/opt/superset/lib/python3.10/site-packages/superset/initialization/__init__.py", line 130, in init_views from superset.cachekeys.api import CacheRestApi File "/opt/superset/lib/python3.10/site-packages/superset/cachekeys/api.py", line 27, in <module> from superset.cachekeys.schemas import CacheInvalidationRequestSchema File "/opt/superset/lib/python3.10/site-packages/superset/cachekeys/schemas.py", line 20, in <module> from superset.charts.schemas import ( File "/opt/superset/lib/python3.10/site-packages/superset/charts/schemas.py", line 427, in <module> class ChartDataAggregateOptionsSchema(ChartDataPostProcessingOperationOptionsSchema): File "/opt/superset/lib/python3.10/site-packages/superset/charts/schemas.py", line 433, in ChartDataAggregateOptionsSchema fields.List( File "/opt/superset/lib/python3.10/site-packages/marshmallow/fields.py", line 711, in __init__ super().__init__(**kwargs) TypeError: Field.__init__() got an unexpected keyword argument &#39;minLength&#39; (superset) superset@VM-0-6-ubuntu:~$
最新发布
11-26
+ skyline-nginx-generator --output-file /etc/nginx/nginx.conf Traceback (most recent call last): File "/usr/local/bin/skyline-nginx-generator", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.10/dist-packages/click/core.py", line 1161, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/click/core.py", line 1082, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.10/dist-packages/click/core.py", line 1443, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python3.10/dist-packages/click/core.py", line 788, in invoke return __callback(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/skyline_apiserver/cmd/generate_nginx.py", line 168, in main endpoints = get_proxy_endpoints() File "/usr/local/lib/python3.10/dist-packages/skyline_apiserver/cmd/generate_nginx.py", line 67, in get_proxy_endpoints endpoints_list = ks_client.endpoints.list(interface=CONF.openstack.interface_type) File "/usr/local/lib/python3.10/dist-packages/keystoneclient/v3/endpoints.py", line 120, in list return super(EndpointManager, self).list( File "/usr/local/lib/python3.10/dist-packages/keystoneclient/base.py", line 85, in func return f(*args, **new_kwargs) File "/usr/local/lib/python3.10/dist-packages/keystoneclient/base.py", line 446, in list list_resp = self._list(url_query, self.collection_key) File "/usr/local/lib/python3.10/dist-packages/keystoneclient/base.py", line 140, in _list resp, body = self.client.get(url, **kwargs) File "/usr/local/lib/python3.10/dist-packages/keystoneauth1/adapter.py", line 673, in get return self.request(url, &#39;GET&#39;, **kwargs) File "/usr/local/lib/python3.10/dist-packages/keystoneauth1/adapter.py", line 657, in request resp = self._request(url, method, **kwargs) File "/usr/local/lib/python3.10/dist-packages/keystoneauth1/adapter.py", line 294, in _request return self.session.req
03-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值