我需要一些帮助来跟踪列表中的索引。我想搜索从列表中获取以前的元素。如果我在列表中有两个元素,我想找到前面的5个元素,这样我就可以将它们存储在列表中。
示例:当变量start_ch
显示列表'421 Eir Sport 1', '422 Eir Sport 2'
中的两个元素时,我想获取'416 BT Sport 2', '417 At the Races', '418 BT Sport ESPN', '419 MUTV', '420 Chelsea TV'
的前5个元素,以将它们存储在连接两个元素的列表中最后的元素。
我想让它显示如下:
['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']
以下是我提取这两个元素时显示的start_ch
:
['421 Eir Sport 1', '422 Eir Sport 2']
以下是self.channel
的列表:
['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']
当我尝试这个时:
for i, start_ch in enumerate(self.channel):
if start_ch == channel:
start_ch = self.channel[i:i+7]
if len(start_ch) == 1:
start_ch = self.channel[i:i-6]
elif len(start_ch) == 2:
start_ch = self.channel[i:i-5]
elif len(start_ch) == 3:
start_ch = self.channel[i:i-4]
elif len(start_ch) == 4:
start_ch = self.channel[i:i-3]
elif len(start_ch) == 5:
start_ch = self.channel[i:i-2]
elif len(start_ch) == 6:
start_ch = self.channel[i:i-1]
print "start_ch"
print start_ch
for channels in start_ch:
print "channels_list"
channels_list.append(channels) #add chanel to list
print channels_list
除了最后两个元素之外,它不会让我从列表中获取前5个元素。
你能告诉我一个例子,除了最后两个元素之外我怎样才能从列表中获取前5个元素,这样我可以将它们连接起来将它们存储在列表中吗?
答案 0 :(得分:2)
喜欢这个(可能):
>>> channel = ['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']
>>> to_find = ['421 Eir Sport 1', '422 Eir Sport 2']
>>> target_index = self.channel.index(to_find[0])
>>> result = channel[target_index-5:target_index] + to_find
>>> result
['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']