0

0

Python - 列表和任务

PHPz

PHPz

发布时间:2024-08-01 21:13:15

|

508人浏览过

|

来源于dev.to

转载

python - 列表和任务

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

不返回

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

返回整数

  • 索引
  • 数数

返回str

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

意兔-AI漫画相机
意兔-AI漫画相机

照片变漫画手绘,做周边好物

下载
  • 流行

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

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

  1. 我们必须逐一迭代列表
  2. 检查项目是字符串还是其他类型
  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 zip
paired_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 for
item_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']*3
print('\t16. notebook list is:', notebook_list)

#filter the list with e letter
delivery_list

new_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 items
delivery_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 comprehension
nested_list = []
for item in delivery_list:
    nested_list.append([item, len(item)])

print('\t17. ', nested_list[-1:-6:-1])

#using list comprehension printing nested list
nested_list = [[item,len(item)] for item in delivery_list]
print('\t17. nested list with length:', nested_list[:5])

答案:

PS C:\Projects\PythonSuresh> 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]]

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
if什么意思
if什么意思

if的意思是“如果”的条件。它是一个用于引导条件语句的关键词,用于根据特定条件的真假情况来执行不同的代码块。本专题提供if什么意思的相关文章,供大家免费阅读。

847

2023.08.22

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

761

2023.08.03

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

221

2023.09.04

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1570

2023.10.24

字符串介绍
字符串介绍

字符串是一种数据类型,它可以是任何文本,包括字母、数字、符号等。字符串可以由不同的字符组成,例如空格、标点符号、数字等。在编程中,字符串通常用引号括起来,如单引号、双引号或反引号。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

651

2023.11.24

java读取文件转成字符串的方法
java读取文件转成字符串的方法

Java8引入了新的文件I/O API,使用java.nio.file.Files类读取文件内容更加方便。对于较旧版本的Java,可以使用java.io.FileReader和java.io.BufferedReader来读取文件。在这些方法中,你需要将文件路径替换为你的实际文件路径,并且可能需要处理可能的IOException异常。想了解更多java的相关内容,可以阅读本专题下面的文章。

1228

2024.03.22

php中定义字符串的方式
php中定义字符串的方式

php中定义字符串的方式:单引号;双引号;heredoc语法等等。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

1205

2024.04.29

go语言字符串相关教程
go语言字符串相关教程

本专题整合了go语言字符串相关教程,阅读专题下面的文章了解更多详细内容。

193

2025.07.29

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

49

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 22.5万人学习

Django 教程
Django 教程

共28课时 | 5万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号