python的列表操作方法_python输入一个列表

python的列表操作方法_python输入一个列表Python 中列表的基本操作包括 访问素 使用下标索引访问列表中的值 pythonfruits banana apple cherry pear fig print fruits 输出 banana 添加素 append object 将值 object 添加到列表的末尾 pythonfruits

Python中列表的基本操作包括:

访问素 :使用下标索引访问列表中的值。

fruits = ['banana', 'apple', 'cherry', 'pear', 'fig']print(fruits) 输出 'banana'

添加素

`append(object)`:将值`object`添加到列表的末尾。

 fruits.append('peach') print(fruits) 输出 ['banana', 'apple', 'cherry', 'pear', 'fig', 'peach'] 

`extend(iterable)`:将另一个可迭代对象中的素添加到列表的末尾。

 more_fruits = ['lemon', 'orange'] fruits.extend(more_fruits) print(fruits) 输出 ['banana', 'apple', 'cherry', 'pear', 'fig', 'peach', 'lemon', 'orange'] 

`insert(index, object)`:在指定位置`index`前插入素`object`。

 fruits.insert(0, 'lemon') print(fruits) 输出 ['lemon', 'banana', 'apple', 'cherry', 'pear', 'fig', 'peach', 'orange'] 

修改素:

直接通过下标赋值修改列表中的素。

 fruits = 'grape' print(fruits) 输出 ['grape', 'apple', 'cherry', 'pear', 'fig', 'peach', 'orange'] 

删除素

`del`:根据下标删除素。

 del fruits print(fruits) 输出 ['grape', 'cherry', 'pear', 'fig', 'peach', 'orange'] 

`pop(index)`:移除列表中指定位置的素,并返回该素的值。

 removed_fruit = fruits.pop(2) print(removed_fruit) 输出 'pear' print(fruits) 输出 ['grape', 'cherry', 'fig', 'peach', 'orange'] 

`remove(object)`:移除列表中第一个匹配的素。

 fruits.remove('cherry') print(fruits) 输出 ['grape', 'fig', 'peach', 'orange'] 

列表操作符

`+`:组合两个列表。

 fruits1 = ['banana', 'apple'] fruits2 = ['cherry', 'pear'] combined_fruits = fruits1 + fruits2 print(combined_fruits) 输出 ['banana', 'apple', 'cherry', 'pear'] 

`*`:重复列表中的素。

 repeated_fruits = ['apple'] * 3 print(repeated_fruits) 输出 ['apple', 'apple', 'apple'] 

其他操作

`len(list)`:获取列表长度。

 print(len(fruits)) 输出 5 

`in`:检查素是否在列表中。

 print('apple' in fruits) 输出 True 

`for`循环遍历列表。

 for fruit in fruits: print(fruit) 

以上是Python列表的一些基本操作。

编程小号
上一篇 2025-02-20 23:21
下一篇 2025-02-20 23:18

相关推荐

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