简体   繁体   中英

Resolving Index out of Range Python

I am trying to add the contents of one list to another across only a select range. I want to create a list of over 700 elements. Than I want to get the elements starting at the 34th element and proceed to grab every 11th element afterwards. But I am having a little issue with resolving the index out of range issue I know the that this issue is caused by pointing to an element that is not present. I also know that the size of a list is affected by counting through it. I'm a little inexperienced with python so I'm not sure how to prevent it in this case. If anyone could help me resolve this Index out of range problem that would be great.

Here is my code:

main_list = []

for i in range(705):
    main_list.append(i)

sublist = []

def my_range(start, end, step):
    while start <= end:
        yield start
        start += step

for x in my_range(34, 705, 11):
    sublist.append(main_list[x])

print sublist

Python indexing is zero based. The last element is at index len(my_list)-1 . You should change the line while start <= end: to while start < end:

In any case, you seem to have reimplemented xrange .

I'll be a little indirect, but there are a few things you can do to better approach this problem. First of all, this:

main_list = []

for i in range(705):
    main_list.append(i)

Could be done with

main_list = range(34, 705)

Range returns a list, so there is no need to populate a different one by iterating over it. Secondly, there are a few ways to get after every eleventh element of the list, but my personal preference when I see something like this is to think of things as a congruence class. So I'd then use something like the following function:

sub_list = []
def eleventh_element(a_list):
    for elem in a_list:
        if (elem - 34) % 11 == 0:
            sub_list.append(elem)

Although in practice it would probably be:

sub_list = filter(lambda x: not ((x - 34) % 11), range(34, 705))

Giving:

>>> sub_list = filter(lambda x: not ((x - 34) % 11), range(34, 705))
>>> sub_list
[34, 45, 56, 67, 78, 89, 100, 111, 122, 133, 144, ...and so on...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM