Python – 列表和任务

python - 列表和任务

学习索引和切片之后,我们开始更多地了解列表和内置方法。方法有

不返回

追加插入删除排序反转清晰

返回整数

索引数数

返回str

立即学习“Python免费学习笔记(深入)”;

流行

对于交付列表的较小更改,内置功能本身就足够了。但是当我们想要对列表进行更多操作时,就需要for循环、if循环。

例如,有一个列表 [‘pencil’, ‘notebook’, ‘marker’, ‘highlighter’, ‘glue stick’, ‘eraser’, ‘laptop’, 3],其中只有字符串需要转换为大写。这里我们不能直接使用列表或字符串方法。理想的逻辑是

我们必须逐一迭代列表检查项目是字符串还是其他类型相应地使用字符串方法 upper() 和append()

所以这里for循环,需要if,else条件

delivery_list= ['pencil', 'notebook', 'marker', 'highlighter', 'glue stick', 'eraser', 'laptop', 3]upper_list = []for item in delivery_list:    if type(item) == str:        upper_list.append(item.upper())    else:        upper_list.append(item)print('upper case list is:', upper_list)output:upper case list is: ['pencil', 'notebook', 'marker', 'highlighter', 'glue stick', 'eraser', 'laptop', 3]

给出的任务是更多地练习这些方法和逻辑。找到可用的逻辑或方法很有趣。
解决的细节是

tasks_list.py########################################################################################1. create a list of five delivery items and print the third item in the list. #eg: [“notebook”, “pencil”, “eraser”, “ruler”, “marker”]#######################################################################################delivery_list = ['notebook', 'pencil', 'eraser', 'ruler', 'marker']print (f't1. third item in the list{delivery_list} is: {delivery_list[2]}')######################################################################################## 2.a new delivery item “glue stick” needs to be added to the list. # add it to the end of the list and print the updated list.#######################################################################################delivery_list.append('glue stick')print('t2. updated delivery list is:', delivery_list)######################################################################################## 3. insert “highlighter” between the second and third items and print the updated list.#######################################################################################delivery_list.insert(2, 'highlighter')print('t3. updated list by inserting highlighter b/w 2nd &3rd:', delivery_list)######################################################################################## 4. one delivery was canceled. remove “ruler” from the list and print the updated list.#######################################################################################delivery_list.remove('ruler')print('t4. updated list after removing ruler is:', delivery_list)######################################################################################## 5. the delivery man needs to deliver only the first three items. # print a sublist containing only these items.#######################################################################################sublist =[]for item in delivery_list[:3]:    #sublist =sublist.append(item)      #this is incorrect as sublist.append() returns none.    sublist.append(item)print('t5. sublist of first three elements using loop:', sublist) print('t   sublist of first three elements using slicing:', delivery_list[:3]) ######################################################################################## 6.the delivery man has finished his deliveries. # convert all item names to uppercase using a list comprehension and print the new list.#######################################################################################uppercase_list=[]for item in delivery_list:    uppercase_list.append(item.upper())print('t6. uppercase list of delivery items:', uppercase_list)uppercase_list_lc = [item.upper() for item in delivery_list]print('t6. uppercase list using list compre:', uppercase_list_lc)######################################################################################## 7. check if “marker” is still in the list and print a message indicating whether it is found.# 8. print the number of delivery items in the list.#######################################################################################is_found= delivery_list.count('marker')if 'marker' in delivery_list:    print(f't7. marker is found {is_found} times')else:    print(f't7. marker is not found {is_found}')print(f't8. number of delivery item from {delivery_list} is: ', len(delivery_list))######################################################################################## 9. sort the list of items in alphabetical order and print the sorted list# 10. the delivery man decides to reverse the order of his deliveries. # reverse the list and print it#######################################################################################delivery_list.sort()print(f't9. sorted delivery list is {delivery_list}')delivery_list.reverse()print(f't10. reverse list of delivery list is {delivery_list}')######################################################################################## 11. create a list where each item is a list containing a delivery item and its delivery time. # print the first item and its time.#######################################################################################delivery_list_time = [['letter', '10:00'], ['parcel', '10:15'], ['magazine', '10:45'], ['newspaper', '11:00']]print('t11. first delivery item and time', delivery_list_time[0])delivery_list = ['pencil', 'notebook', 'marker', 'highlighter', 'glue stick', 'eraser', 'laptop']delivery_time = ['11:00','11:20','11:40','12:00','12:30','13:00', '13:30']#paring of two list using zippaired_list=list(zip(delivery_list,delivery_time))print('tpaired list using zip:', paired_list[0:2])#combine corresponding item from multiple list using zip and foritem_time_list = [[item,time] for item, time in zip(delivery_list, delivery_time)]print ('titem_time_list using list comprehension: ', item_time_list[0:1])######################################################################################## 12. count how many times “ruler” appears in the list and print the count.# 13. find the index of “pencil” in the list and print it.# 14. extend the list items with another list of new delivery items and print the updated list.# 15. clear the list of all delivery items and print the list.# 16. create a list with the item “notebook” repeated three times and print the list.# 17. using a nested list comprehension, create a list of lists where each sublist contains an item # and its length, then print the new list.# 18. filter the list to include only items that contain the letter “e” and print the filtered list.# 19. remove duplicate items from the list and print the list of unique items.#######################################################################################is_found= delivery_list.count('ruler')print('t12. the count of ruler in delivery list is:', is_found)index_pencil = delivery_list.index('pencil')print(f't13. index of pencil in {delivery_list} is {index_pencil}')small_list = ['ink','']delivery_list.extend(small_list)print('t14. extend list by extend:', delivery_list)item_time_list.clear()print('t15. clearing the list using clear():', item_time_list)notebook_list = ['notebook']*3print('t16. notebook list is:', notebook_list)#filter the list with e letterdelivery_listnew_delivery_list = []for item in delivery_list:    if 'e' in item:        new_delivery_list.append(item)print ('t18. filtered list with items containing e:', new_delivery_list)new_list_compre = [item for item in delivery_list if 'e' in item]print ('t18. filtered list by list comprehension:', new_list_compre)#remove duplicate itemsdelivery_list.extend(['ink', 'marker'])print('t   ', delivery_list)for item in delivery_list:    if delivery_list.count(item) > 1:        delivery_list.remove(item)print('t19. duplicate remove list:',delivery_list)print('t19. duplicate remove list:',list(set(delivery_list)))######################################################################################## 17. using a nested list comprehension, create a list of lists where each sublist contains an item # and its length, then print the new list.########################################################################################without list comprehensionnested_list = []for item in delivery_list:    nested_list.append([item, len(item)])print('t17. ', nested_list[-1:-6:-1])#using list comprehension printing nested listnested_list = [[item,len(item)] for item in delivery_list]print('t17. nested list with length:', nested_list[:5])

答案:

PS C:ProjectsPythonSuresh> python Tasks_list.py        1. Third item in the list['Notebook', 'Pencil', 'Eraser', 'Ruler', 'Marker'] is: Eraser        2. Updated delivery list is: ['Notebook', 'Pencil', 'Eraser', 'Ruler', 'Marker', 'Glue Stick']        3. Updated list by inserting Highlighter b/w 2nd &3rd: ['Notebook', 'Pencil', 'Highlighter', 'Eraser', 'Ruler', 'Marker', 'Glue Stick']        4. Updated list after removing Ruler is: ['Notebook', 'Pencil', 'Highlighter', 'Eraser', 'Marker', 'Glue Stick']        5. Sublist of first three elements using loop: ['Notebook', 'Pencil', 'Highlighter']           Sublist of first three elements using slicing: ['Notebook', 'Pencil', 'Highlighter']        6. Uppercase list of delivery items: ['NOTEBOOK', 'PENCIL', 'HIGHLIGHTER', 'ERASER', 'MARKER', 'GLUE STICK']        6. Uppercase list using list compre: ['NOTEBOOK', 'PENCIL', 'HIGHLIGHTER', 'ERASER', 'MARKER', 'GLUE STICK']        7. Marker is found 1 times        8. Number of delivery item from ['Notebook', 'Pencil', 'Highlighter', 'Eraser', 'Marker', 'Glue Stick'] is:  6        9. Sorted delivery list is ['Eraser', 'Glue Stick', 'Highlighter', 'Marker', 'Notebook', 'Pencil']        10. Reverse list of delivery list is ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser']        11. First delivery item and time ['Letter', '10:00']        Paired list using zip: [('Pencil', '11:00'), ('Notebook', '11:20')]        Item_time_list using list comprehension:  [['Pencil', '11:00']]        12. The count of Ruler in delivery list is: 0        13. Index of Pencil in ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser', 'Laptop'] is 0        14. Extend list by extend: ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser', 'Laptop', 'Ink', '']        15. Clearing the list using clear(): []        16. Notebook list is: ['Notebook', 'Notebook', 'Notebook']        18. Filtered list with items containing e: ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser']        18. Filtered list by list comprehension: ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser']            ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser', 'Laptop', 'Ink', '', 'Ink', 'Marker']        19. Duplicate remove list: ['Pencil', 'Notebook', 'Highlighter', 'Glue Stick', 'Eraser', 'Laptop', '', 'Ink', 'Marker']        19. Duplicate remove list: ['', 'Ink', 'Pencil', 'Notebook', 'Marker', 'Eraser', 'Laptop', 'Highlighter', 'Glue Stick']        17.  [['Marker', 6], ['Ink', 3], ['', 0], ['Laptop', 6], ['Eraser', 6]]        17. Nested list with length: [['Pencil', 6], ['Notebook', 8], ['Highlighter', 11], ['Glue Stick', 10], ['Eraser', 6]]

以上就是Python – 列表和任务的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1348669.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Python:全面介绍
上一篇 2025年12月13日 12:14:37
在 Python 中使用 SQLAlchemy 创建关系
下一篇 2025年12月13日 12:14:57

相关推荐

  • Matplotlib 地图中多类型图例的创建与优化

    Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化

    本教程旨在解决matplotlib地图可视化中,如何在一个图例中同时展示颜色块(如区域分类)和自定义标记(如特定兴趣点)的问题。文章详细介绍了当传统`patch`对象无法正确显示标记时,如何利用`matplotlib.lines.line2d`创建标记图例句柄,并将其与颜色块图例句柄合并,从而生成一…

    2026年5月10日 用户投稿
    100
  • 利用海象运算符简化条件赋值:Python教程与最佳实践

    本文旨在探讨Python中海象运算符(:=)在条件赋值场景下的应用。通过对比传统if/else语句与海象运算符,以及条件表达式,分析海象运算符在简化代码、提高可读性方面的优势与局限性。并通过具体示例,展示如何在列表推导式等场景下合理使用海象运算符,同时强调其潜在的复杂性及替代方案,帮助开发者更好地掌…

    2026年5月10日
    100
  • RichHandler与Rich Progress集成:解决显示冲突的教程

    在使用rich库的`richhandler`进行日志输出并同时使用`progress`组件时,可能会遇到显示错乱或溢出问题。这通常是由于为`richhandler`和`progress`分别创建了独立的`console`实例导致的。解决方案是确保日志处理器和进度条组件共享同一个`console`实例…

    2026年5月10日
    000
  • 使用 Jupyter Notebook 进行探索性数据分析

    Jupyter Notebook通过单元格实现代码与Markdown结合,支持数据导入(pandas)、清洗(fillna)、探索(matplotlib/seaborn可视化)、统计分析(describe/corr)和特征工程,便于记录与分享分析过程。 Jupyter Notebook 是进行探索性…

    2026年5月10日
    000
  • Python命令怎样使用profile分析脚本性能 Python命令性能分析的基础教程

    使用Python的cProfile模块分析脚本性能最直接的方式是通过命令行执行python -m cProfile your_script.py,它会输出每个函数的调用次数、总耗时、累积耗时等关键指标,帮助定位性能瓶颈;为进一步分析,可将结果保存为文件python -m cProfile -o ou…

    2026年5月10日
    000
  • Python递归函数追踪与性能考量:以序列打印为例

    本文深入探讨了Python中一种递归打印序列元素的方法,并着重演示了如何通过引入缩进参数来有效追踪递归函数的执行流程和参数变化。通过实际代码示例,文章揭示了递归调用可能带来的潜在性能开销,特别是对调用栈空间的需求,以及Python默认递归深度限制可能导致的错误,为读者提供了理解和优化递归算法的实用见…

    2026年5月10日
    000
  • python中zip函数详解 python多序列压缩zip函数应用场景

    zip函数的应用场景包括:1) 同时遍历多个序列,2) 合并多个列表的数据,3) 数据分析和科学计算中的元素运算,4) 处理csv文件,5) 性能优化。zip函数是一个强大的工具,能够简化代码并提高处理多个序列时的效率。 在Python中,zip函数是一个非常有用的工具,它能够将多个可迭代对象打包成…

    2026年5月10日
    000
  • Python中怎样使用pymongo?

    在python中使用pymongo可以轻松地与mongodb数据库进行交互。1)安装pymongo:pip install pymongo。2)连接到mongodb:from pymongo import mongoclient; client = mongoclient(‘mongod…

    2026年5月10日
    000
  • Python 函数参数类型:如何使用可变参数和动态参数?

    python 中的参数类型:关键词参数、可变参数和动态参数 在 python 中,函数的参数可以分为以下几种类型: 关键词参数(kw)**:这些参数具有名称,并且在调用函数时明确指定。可变参数(*args):这些参数没有名称,允许函数接受任意数量的位置参数。它们将被收集到一个元组中。动态参数(kwa…

    2026年5月10日
    000
  • pycharm解析器怎么添加 解析器添加详细流程

    在pycharm中添加解析器的步骤包括:1) 打开pycharm并进入设置,2) 选择project interpreter,3) 点击齿轮图标并选择add,4) 选择解析器类型并配置路径,5) 点击ok完成添加。添加解析器后,选择合适的类型和版本,配置环境变量,并利用解析器的功能提高开发效率。 在…

    2026年5月10日
    000
  • python中numpy的用法

    NumPy是Python中用于科学计算的强大库,它提供了以下功能:多维数组处理矩阵运算快速傅里叶变换(FFT)线性代数随机数生成 NumPy在Python中的强大功能 NumPy是Python中用于科学计算的一个强大且灵活的库。它提供了用于处理多维数组和矩阵的一组高效工具,是数据分析和机器学习项目的…

    2026年5月10日
    100
  • python如何捕获所有类型的异常_python try except捕获所有异常的方法

    答案:捕获所有异常推荐使用except Exception as e,可捕获常规错误并记录日志,避免影响程序正常退出;需拦截系统信号时才用except BaseException as e。 在Python中,要捕获所有类型的异常,最常见且推荐的方法是使用 except Exception as e…

    2026年5月10日
    000
  • python中f怎么用

    f-字符串是 Python 3.6 中引入的格式化字符串语法糖,提供了简洁且安全的方式来插入表达式和变量。f-字符串以字符串前缀 f 为标志,使用大括号包含表达式或变量。f-字符串支持条件表达式和格式规范符,提供了更大的灵活性、安全性、可读性和易维护性。 在 Python 中使用 f-字符串 f-字…

    2026年5月10日
    100
  • 怎么在手机上把XML文件转换为PDF?

    不可能直接在手机上用单一应用完成 XML 到 PDF 的转换。需要使用云端服务,通过两步走的方式实现:1. 在云端转换 XML 为 PDF,2. 在手机端访问或下载转换后的 PDF 文件。 怎么在手机上把XML文件转换为PDF? 这问题问得好,比直接问“怎么转换”有深度多了!因为它触及了移动端环境的…

    2026年5月10日
    000
  • ReCAPTCHA V3低分处理策略:结合V3与V2实现智能风险控制与用户验证

    本文旨在解决ReCAPTCHA V3在低分情况下无法直接触发验证码挑战的问题。我们将探讨如何通过巧妙地结合ReCAPTCHA V3的无感评分机制与ReCAPTCHA V2的交互式挑战,实现一套既能有效阻挡机器人流量,又能最大限度减少对合法用户干扰的智能验证系统。文章将详细阐述其实现原理、前端与后端集…

    2026年5月10日
    100
  • Python正则表达式:处理数字不同情况的替换

    本文旨在帮助读者理解和解决在使用Python正则表达式进行数字替换时遇到的问题。通过具体示例,详细解释了如何正确匹配和替换不同格式的数字,避免常见的匹配陷阱,并提供可直接使用的代码示例。掌握这些技巧,能有效提高处理文本数据的效率和准确性。 在使用Python的re模块进行字符串替换时,正则表达式的编…

    2026年5月10日
    000
  • python的tuple什么意思

    元组是Python中一种有序、不可变的序列数据结构。用于存储相关数据,例如坐标、个人信息或枚举值。创建方式:圆括号(),元素以逗号,分隔。访问元素:索引运算符;遍历元素:for循环。 什么是Python中的Tuple? Tuple,中文称为元组,是Python中一种有序、不可变的序列数据结构。 特点…

    2026年5月10日
    000
  • Python官网用户调查的参与方式_Python官网反馈提交详细教程

    答案是通过访问Python官网新闻页面、邮件邀请链接或GitHub仓库提交反馈。具体为:访问官网查找用户调查公告,或点击邮件中的专属链接参与,在GitHub的cpython仓库提交技术建议,并注意如实填写问卷与保护隐私。 如果您希望参与Python官网的用户调查并提交反馈,可以通过官方指定的渠道完成…

    2026年5月10日
    000
  • 我有时使用 awk 而不是 Python 的四个原因

    Python 是一门强大的编程语言,但在某些特定场景下,Awk 的优势更为显著,尤其体现在可移植性、生命周期、代码简洁性和与其他工具的互操作性方面。 Python 脚本通常具有良好的可移植性,但并非总能在所有环境中完美运行,例如流行的 Docker 基础镜像 (如 Debian 和 Alpine)。…

    2026年5月10日
    000
  • Python字符串格式化进阶:解包与f-string的巧妙应用

    本文深入探讨了Python中字符串格式化的多种方法,重点讲解了元组解包与f-string的结合使用。通过示例代码,详细比较了%操作符、str.format()方法以及f-string在元组解包场景下的应用,并提供了在f-string中使用斜杠分隔符的更简洁方案,旨在帮助读者掌握更高效、更易读的字符串…

    2026年5月10日
    000

发表回复

登录后才能评论
关注微信