python 历遍_python遍历

#coding=utf-8

#!/usr/bin/python3

vec = [2,4,6]

x = [3 * x for x in vec]

print x

x = [[x,x ** 2] for x in vec]

print x

1.对序列里每一个元素逐一调用某方法

freshfruit = [' banana', ' loganberry ', 'passion fruit ']

x = [x.strip() for x in freshfruit] #将元素的每个元素去除空格

print x

2.还可以用if 语句作为过滤器

x = [3 * x for x in vec if x > 3] # 这句话的含义是 如果x > 3 将x * 3 生成新数组

print x # [12,18]

vec1 = [2,4,6]

vec2 = [1,3,5]

x = [ x * y for x in vec1 for y in vec2 if y > x] # 此时只有 3对符合要求 x= 2 y = 3, x= 2 y = 5, x = 4 y= 10

print x # [6,10,20]

3.del关键字的使用

a = [-1, 1, 66.25, 333, 333, 1234.5]

del a[2:4]

print a

a = [-1, 1, 66.25, 333, 333, 1234.5] ## 从第2个元素开始到第4个元素截止 不包含第四个元素

del a[1:3]

print a

4.如果创建空集合必须用set()

x = set()

5.字典的遍历

dic1 = {"url":"www.baidu.com","address":"nanping"}

for k,v in dic1.items():

print (k,v)

6.数组的遍历

list1 = ["ac","bc","cc","dc","ec"]

for index,item in enumerate(list1):

print (index,item) # 打印出索引和元素

7.同时遍历两个或更多的序列,可以使用 zip() 组合

questions = ['name', 'quest', 'favorite color']

answers = ['lancelot', 'the holy grail', 'blue']

for q,a in zip(questions,answers):

print("what is your {0}? it is {1}".format(q,a))

# print('what is your %s? it is %s' %(q,a)) 也可以用这种方式

s = 'what is your %s? it is %s' %(q,a) #

print type(s) # str

8.反向遍历 如果数据是根据时间存储的。我们取出的时候 最后存的放在最下面了。这时候反向遍历就很有用

for i in reversed(range(10)): # 反向遍历

print i

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值