Home > Backend Development > Python Tutorial > 初学python数组的处理代码

初学python数组的处理代码

WBOY
Release: 2016-06-06 11:27:37
Original
1829 people have browsed it

初学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]


当时我就傻眼了,后来缘缘又出了道题目:

造一个 200 个随机正整数(1~15)的list
统计其中 正整数的出现次数,并排序输出结果

开始的时候,不清楚random居然还要import。。。。

后来花了好久做出来:

代码如下:


>>> 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)]


缘缘点评循环的时候,可以用Get比如

代码如下:


for i in mylist:
s[i]=s.get(i,0)+1


然后说sorted可以有从大到小的倒排,后来找了一下资料,发现可以这样
sorted(d.items(),cmp=lambda x,y:cmp(x[1],y[1]),reverse=True)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template