Python Learning Essay 1

Source: Internet
Author: User

In a list, find the location of the repeating array.

For example, in the list name = [1, 5, 8, 22, 56, 2, 8, 45, 7, 2, 35, 2, 486, 2, 152, 111, 265, 2, 2], locate the 2 position.

Method 1:

The process is:

Find the first 2 position, then slice after a number after 2, then look for 2, then the next number of slices, loop down.

The first 2 position is the first 2 position in name.

The position of the second 2 is the position of the first 2 plus the 2 position in the second slice plus 1 (position starting from 0)

The third and so on.

Code:

#_*_coding:utf-8_*_name= [1, 5, 8, 22, 56, 2, 8, 45, 7, 2, 35, 2, 486, 2, 152, 111, 265, 2, 2]new_pos= 0#initial position Positioning 0 forIinchRange (Name.count (2)):#number of occurrences for the For loop number 2New_list = Name[new_pos:]#slices, from the first 0 slices, implement new_list = nameNext_pos = New_list.index (2)#the first 2 position to find    PrintNext_pos + New_pos#position of output 2, plus next position from new positionNew_pos + = Next_pos + 1#The new position adds one to the next position, because the slice starts at a number after 2, or the next 2 position is permanently 0

Output Result:

Method 2 (Hyper-violence):

The process is:

Starting from the first 2, each time the position of 2 is deleted, the next 2 of the position plus the number of deleted 2.

The code is as follows:

# _*_coding:utf-8_*_  = [1, 5, 8, 8, 2, 7,, 2, 2,, 2, 486, 2,, 2]for in# Number of cycles as 2 occurrences in the list    Print # The position of the output 2 plus the number of I, I is 0, 1, 2, 3 ... Just delete the number of times 2    del#  Delete the current output of 2, form a new list into the next loop

Output Result:

Python Learning Essay 1

Related Article

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.