初学python,小缘缘出了几道题:
有一 list
a = [1, 2, 3, 4, 5, 6]
请将 a 依
0, 1
1, 2
2, 3
3, 4
4, 5
5, 6
打印输出,
2.将a list 倒序成 [6, 5, 4, 3, 2, 1]
3.将a 中的偶数挑出 *2 ,结果为 [4, 8, 12]
基本上实现:
代码如下:
a=[1,2,3,4,5,6]
for i in a:
print a.index(i),',',i
a.reverse();
print a
for i in a:
if i%2==0
print i*2
代码如下:
for k,v in enumerate(a):
print k,v
print a[::-1]
print [i*2 for i in a if not i%2]
代码如下:
>>> import random
>>> mylist = [random.randint(1,15) for i in range(1,200)]
>>> s={}
>>> for i in mylist:
if not s.has_key(i):
s[i]=0
else:
s[i]+=1
>>> cmplist = sorted(s.items(),key=lambda(d):d[1])
>>> result = cmplist[::-1]
>>> print result
[(8, 20), (13, 19), (12, 16), (9, 15), (6, 15), (3, 14), (2, 12), (14, 11), (4, 11), (15, 10), (7, 10), (11, 9), (5, 9), (1, 9), (10, 4)]
代码如下:
for i in mylist:
s[i]=s.get(i,0)+1