python开发之for循环操作实例详解

yipeiwu_com5年前Python基础

本文实例讲述了python开发之for循环操作。分享给大家供大家参考,具体如下:

下面是我做的一些学习记录供大家参考:

#基本的for循环语句
test_list = [2,"Jone",3,6,7,'hongten','hanyuan','good',"Tom"]
#打印列表的长度
print(len(test_list))
#遍历列表
for i in test_list:
  print(i)
test_str = "hello,i'm hongten"
print('打印字符串:' + test_str)
#遍历一个字符串
print('遍历一个字符串')
for i in test_str:
  print(i)
test_tuple = [("a",1),("b",2),("c",3),("d",4)]
print(test_tuple)
#遍历一个元组
print('遍历一个元组')
for (i,j) in test_tuple:
  print(i,j)
test_dict = {'name':'hongten','age':'20','gender':'M','sports':'足球,乒乓球,游泳'}
#字典迭代器
for key in test_dict:
  print(key + ':' + test_dict[key])
L1 = [1,3,5,7]
L2 = [2,4,6,8]
#使用zip将两个列表合并
print(zip(L1,L2))
for (i,j) in zip(L1,L2):
  print(i,j)
print('#######################################################')
L3 = L2[:]
L3.remove(8)
print('L1,L3列表为:')
print(L1)
print(L3)
for (i,j) in zip(L1,L3):
  print(i,j)
#可以看出来当长度不一的时候,多余的被忽略
test_keys = ['name','age','gender','weight','hight']
test_values = ['Hongten','20','M','55','170']
#使用zip来构造一个字典
print('字典中的keys:')
print(test_keys)
print('字典中的key对应的value:')
print(test_values)
print('构造字典后')
test_dic = dict(zip(test_keys,test_values))
for key in test_dic:
  print( key + ':' + test_dic[key])

运行效果:

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
9
2
Jone
3
6
7
hongten
hanyuan
good
Tom
打印字符串:hello,i'm hongten
遍历一个字符串
h
e
l
l
o
,
i
'
m
 
h
o
n
g
t
e
n
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
遍历一个元组
('a', 1)
('b', 2)
('c', 3)
('d', 4)
gender:M
age:20
name:hongten
sports:足球,乒乓球,游泳
[(1, 2), (3, 4), (5, 6), (7, 8)]
(1, 2)
(3, 4)
(5, 6)
(7, 8)
#######################################################
L1,L3列表为:
[1, 3, 5, 7]
[2, 4, 6]
(1, 2)
(3, 4)
(5, 6)
字典中的keys:
['name', 'age', 'gender', 'weight', 'hight']
字典中的key对应的value:
['Hongten', '20', 'M', '55', '170']
构造字典后
gender:M
age:20
name:Hongten
weight:55
hight:170
>>>

希望本文所述对大家Python程序设计有所帮助。

相关文章

opencv3/C++图像像素操作详解

opencv3/C++图像像素操作详解

RGB图像转灰度图 RGB图像转换为灰度图时通常使用: 进行转换,以下尝试通过其他对图像像素操作的方式将RGB图像转换为灰度图像。 #include<opencv2/open...

python中threading超线程用法实例分析

本文实例讲述了python中threading超线程用法。分享给大家供大家参考。具体分析如下: threading基于Java的线程模型设计。锁(Lock)和条件变量(Condition...

Python中如何获取类属性的列表

前言 最近工作中遇到个需求是要得到一个类的静态属性,也就是说有个类 Type ,我要动态获取 Type.FTE 这个属性的值。 最简单的方案有两个: getattr(Type, 'F...

python随机数分布random均匀分布实例

python随机数分布random均匀分布实例

因为概率问题,所以需要测试一下python的随机数分布。到底是平均(均匀)分布,还是正态(高斯)分布。 测试代码如下: #! /usr/bin/env python #coding=...

python中列表元素连接方法join用法实例

本文实例讲述了python中列表元素连接方法join用法。分享给大家供大家参考。具体分析如下: 创建列表: >>> music = ["Abba","Rollin...