简体   繁体   中英

How to check the index value from the list in python

I need some help with my code. I want to check that if the value for self.channels_index is no greater or equal than self.channel so I can fetch the element from the list. If the value is greater than self.channel value then don't do anything.

When I try this:

self.channels_Index += 1

for index in enumerate(self.channel):
    if index > self.channels_Index:
       new_channel = self.channel[self.channels_Index]

I will get an error: IndexError: list index out of range.

The error are highlight on this line:

new_channel = self.channel[self.channels_Index]

There is no value after the last element from the list.

Here is the self.channel list:

 ['101 BBC One S East', '102 BBC Two', '103 ITV', '104 Channel 4', '105 Channel 5', '106 Sky One', '107 Sky Living', '108 Sky Atlantic', '401 Sky Sports 1 UK', '402 SKY Sports 2 UK', '403 Sky Sports 3 UK', '404 Sky Sports 4 UK', '405 Sky Sports 5 UK', '406 Sky Sports News HQ', '407 Sky Sports F1', '408 Sky Sports 1 HD', '409 Sky Sports 2 HD', '410 Sky Sports 3 HD', '411 Sky Sports 4 HD', '412 Sky Sports 5 HD', '413 Eurosport 1 UK', '414 Eurosport 2 UK', '415 BT Sport 1', '416 BT Sport 2', '417 At the Races', '418 BT Sport ESPN', '419 MUTV', '420 Chelsea TV', '421 Eir Sport 1', '422 Eir Sport 2']

What I am expecting to achieve is I am using the self.channels_index to add the value and check with the self.channel value so I can fetch the element using the value until I can get the last element from the list which it is 422 Eir Sport 2

Can you please show me an example how I can use self.channels_index to check with the self.channel value to see that if the value is equal or no greater than the last value so I can fetch the elements until I can get the last element from the list?

enumerate() returns a list of indexes and values. Observe:

>>> L = ['hi', 'hello', 'hey']
>>> list(enumerate(L))
[(0, 'hi'), (1, 'hello'), (2, 'hey')]

You'll need to modify your code to reflect this by having two variables in your for loop:

for index, val in enumerate(self.channel):
    if index > self.channels_Index:
       new_channel = val

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