Python序列迭代

1、数字(number):

for i in range(0,20,2):
    print(i,end=' , ')

运行结果:

 0 , 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 , 

2、字符串(string):

string='what a wonderful world!'
for i in string:
    print(i,end=' , ')

运行结果: 

w , h , a , t ,   , a ,   , w , o , n , d , e , r , f , u , l ,   , w , o , r , l , d , ! ,

3、列表(list):

list=[5,5.3,'%hello%',[1,2],{'a':125}]
for i in list:
    print(i,end=' , ')

运行结果:

5 , 5.3 , %hello% , [1, 2] , {'a': 125} , 

4、元组(tuple):

tuple=(5,3.2,'$well',('a','b'),[5,3])
for i in tuple:
    print(i,end=' , ')

运行结果:

5 , 3.2 , $well , ('a', 'b') , [5, 3] , 

Python中的可迭代对象是指可以使用循环结构(如`for`循环)依次访问其中元素的对象。在Python中,常见的可迭代对象分为**序列类型****非序列类型**。以下将重点介绍**序列类型**的可迭代对象及其使用方法。 ### 列表(`list`) 列表是Python中最常用的可变序列类型,它允许存储多个元素,并支持索引访问、切片操作迭代。 #### 使用方法: - **创建列表**: ```python my_list = [1, 2, 3, 4, 5] ``` - **遍历列表**: ```python for item in my_list: print(item) ``` - **索引访问**: ```python print(my_list[0]) # 输出第一个元素 ``` - **切片操作**: ```python print(my_list[1:3]) # 输出索引1到2的元素 ``` - **添加元素**: ```python my_list.append(6) # 添加元素到末尾 ``` - **删除元素**: ```python del my_list[0] # 删除索引为0的元素 ``` ### 元组(`tuple`) 元组是不可变的序列类型,一旦创建,其内容无法修改。它通常用于存储不希望被更改的数据。 #### 使用方法: - **创建元组**: ```python my_tuple = (1, 2, 3, 4, 5) ``` - **遍历元组**: ```python for item in my_tuple: print(item) ``` - **索引访问**: ```python print(my_tuple[0]) # 输出第一个元素 ``` - **切片操作**: ```python print(my_tuple[1:3]) # 输出索引1到2的元素 ``` ### 字符串(`str`) 字符串是不可变的序列类型,用于存储文本数据。每个字符在字符串中都有一个索引位置。 #### 使用方法: - **创建字符串**: ```python my_string = "Hello, World!" ``` - **遍历字符串**: ```python for char in my_string: print(char) ``` - **索引访问**: ```python print(my_string[0]) # 输出第一个字符 ``` - **切片操作**: ```python print(my_string[7:12]) # 输出子字符串"World" ``` - **字符串拼接**: ```python new_string = my_string + " How are you?" ``` - **字符串格式化**: ```python name = "Alice" greeting = f"Hello, {name}!" ``` ### 使用可迭代对象的优势 - **简化循环**:通过可迭代对象,可以轻松地使用`for`循环遍历所有元素,而无需手动管理索引。 - **提高代码可读性**:使用可迭代对象可以让代码更简洁、易读。 - **支持函数式编程**:许多Python内置函数(如`map()`、`filter()`)都接受可迭代对象作为参数,便于进行函数式编程操作。 ### 示例:结合列表元组进行数据处理 ```python # 使用列表存储多个数据 data_list = [10, 20, 30, 40, 50] # 使用元组存储固定配置 config_tuple = ("host", 8080, "localhost") # 遍历列表并输出每个元素 for item in data_list: print(item) # 遍历元组并输出每个元素 for item in config_tuple: print(item) ``` ### 总结 Python中的可迭代对象(尤其是序列类型)为数据处理提供了极大的便利。列表、元组字符串是最常见的序列类型,它们各自具有不同的特性使用场景。通过合理使用这些可迭代对象,可以编写出更加高效、简洁的代码[^1]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值