Learning Python array processing code _python

Source: Internet
Author: User
Beginners python, a small margin of a few problems:
There is a list
A = [1, 2, 3, 4, 5, 6]
Please put a according to
0, 1
1, 2
2, 3
3, 4
4, 5
5, 6
Print output,
2. Reverse a list to [6, 5, 4, 3, 2, 1]
3. Select the even number in a *2, the result is [4, 8, 12]

Basically achieve:
Copy Code code as follows:

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 margin said the answer is not good, he replied
Copy Code code as follows:

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 edge of the road and a problem:

Create a list of 200 random positive integers (1~15)
Count the occurrences of positive integers and sort the output

At the beginning, it is not clear random unexpectedly also import ....

Then it took me a long time to do it:
Copy Code code as follows:

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

Margin comments on the cycle, you can use get such as
Copy Code code as follows:

For I in MyList:
S[i]=s.get (i,0) +1

Then said sorted can have from the big to small inverted row, and then looked for information, found that you can
Sorted (D.items (), Cmp=lambda x,y:cmp (x[1],y[1)), reverse=true)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.