标签:python
1,显示列表所有元素
逆向打印
说明:
len()函数统计序列字符串个数。
pop()函数默认是从序列最后往前打印的。
l1[0] 表示打印第0个元素;l1.pop(0) 弹出,第0个元素,以此弹出,打印。-1代表最大列表的索引。
count = 0
while l1:
if l1[count]%2 == 0:
l1[count]
2,将序列l1和l2组合为字典
l1 = [0,1,2,3,4]
l2 = ["Sun","Mon","Tue","Wed","Thu"]
d1 = {}
count = 0
while count < len(l1):
d1[l1[count]] = l2[count]
count += 1
print d1
3,1到100的和
sum = 0
for i in xrange(1,101): #或者range,range是在内存先生成序列,再参与语句计算,而xrange是用一个生成一个
sum += i
print sum
bash shell:
#!/bin/bash
sum=0
for i in `seq 1 100`
do
sum=$((sum+i))
done
echo $sum
4,用户输入的添加到制定列表,q退出
test = []
while True: #死循环
x = raw_input(‘Eenter an entry: ‘) #提示输入,提示字符
if x == ‘q‘ or x ==‘quit‘:
break
else:
test.append(x) #添加列表的函数。
5,将字典内k,v逐一显示
d1 = {‘a‘:1,‘b‘:2,‘c‘:3}
#d1.items() #遍历d1
#Out[12]: [(‘a‘, 1), (‘c‘, 3), (‘b‘, 2)]
for (k,v) in di.items(): #使用元组的方式定义变量。
print k,v
6,将列表内容索引为基数的打印出来。
l1 = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
for i in range(1,len(l1),2): #range(1,len(l1),2) 从1开始,到列表的长度,步长为2
print l1[i]
7,将属于列表l1=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],但不属于列表l2=["Sun","Mon","Tue","Thu","Sat"]的所有元素定义为一个新列表l3;
l3 = []
for i in range(0,len(l1)): #使用索引数字序列。
if l1[i] not in l2:
l3.append(l1[i])
l3 = []
for i in l1:
if i not in l2:
l3.append(i)
8,已知列表namelist=[‘stu1‘,‘stu2‘,‘stu3‘,‘stu4‘,‘stu5‘,‘stu6‘,‘stu7‘],删除列表removelist=[‘stu3‘, ‘stu7‘, ‘stu9‘];请将属于removelist列表中的每个元素从namelist中移除(属于removelist,但不属于namelist的忽略即可);
for i in removelist:
if i in namelist:
namelist.remove(i) #remove()函数删除一个元素。pop是弹出一个索引序列
namelist.pop(4)
‘stu6‘
,9,并行迭代
l1 = [1,2,3]
l2 = [‘x‘,‘y‘,‘z‘]
zip(l1,l2)
[(1, ‘x‘), (2, ‘y‘), (3, ‘z‘)]
标签:python
原文地址:http://disheng.blog.51cto.com/2821957/1754593