#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
网友评论