Learn how to handle python arrays

  • 2020-04-02 09:29:41
  • OfStack

When I first learned python, I got a few questions:
There is a list
A = [1, 2, 3, 4, 5, 6]
Please send in a
0, 1
1, 2
2, 3
3, 4
4, 5
5, 6
Print out,
2. Reverse order a list into [6, 5, 4, 3, 2, 1]
3. Pick the even number in a *2, the result is [4, 8, 12]

Basically achieve:
 
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 

Although all finished, but the small edge edge said the answer is not good, he replied so
 
for k,v in enumerate(a): 
print k,v 
print a[::-1] 
print [i*2 for i in a if not i%2] 

At that time, I was dumbfounded, and then the fate of the question:

Make a list of 200 random positive integers (1 to 15)
Count the occurrence times of positive integers and sort the output results

At first, it wasn't clear that random had to import...

It took a long time to make:
 
>>> 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)] 

When commenting on a loop, you can use Get, for example
 
for i in mylist: 
s[i]=s.get(i,0)+1 

Then I said, "I have sorted, I have sorted backwards from large to small
Sorted (d.i tems (), CMP = lambda x, y: CMP (x [1], [1] y), reverse = True)

Related articles: