猿问

将列表的元素附加到迭代器的左侧或右侧到另一个列表

您可以使用在每次迭代中都会发生变化的变量;


看到这个:-


>>> list1 = [ 'a', 'b', 'c', 'd' ]

>>> 

>>> var, list2 = 0, []

>>> for i in list1:

...     filename = 'file{}'.format(var)

...     var += 1

...     list2.append(filename)

... 

>>> list2

['file0', 'file1', 'file2', 'file3']


红颜莎娜
浏览 176回答 3
3回答

守着一只汪

就个人而言,我认为使用单词的索引来查找比循环遍历列表更容易。complete_word_list = ['3', 'May', '.', 'Bistritz', '.', 'Left', 'Munich', 'at', '8:35', 'P.', 'M.', ',', 'on', '1st', 'May', ',', 'arriving', 'atVienna', 'early', 'next', 'morning', ';', 'should', 'have', 'arrived', 'at', '6:46', ',', 'but', 'train', 'dracula', 'anhour', 'late']dracula_list = ['dracula','Dracula']nearby_words = []for i in dracula_list:&nbsp; &nbsp; if i in complete_word_list: #if word was found in list&nbsp; &nbsp; &nbsp; &nbsp; found_word = complete_word_list.index(i) #returns index of word to find&nbsp; &nbsp; &nbsp; &nbsp; nearby_words.append(complete_word_list[found_word-1]) #index-1 is the element to the left&nbsp; &nbsp; &nbsp; &nbsp; if found_word+1 < len(complete_word_list): #include a check to keep indices in range of list&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nearby_words.append(complete_word_list[found_word+1]) #index+1 is element to the rightprint(nearby_words)编辑:按照建议,您可以使用try and exceptcatch 来检查元素是否在列表中 ( ValueError) 或者是否有任何相邻元素 ( IndexError):complete_word_list = ['3', 'May', '.', 'Bistritz', '.', 'Left', 'Munich', 'at', '8:35', 'P.', 'M.', ',', 'on', '1st', 'May', ',', 'arriving', 'atVienna', 'early', 'next', 'morning', ';', 'should', 'have', 'arrived', 'at', '6:46', ',', 'but', 'train', 'dracula', 'anhour', 'late']dracula_list = ['dracula','Dracula']nearby_words = []for i in dracula_list:&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; found_word = complete_word_list.index(i)&nbsp; &nbsp; &nbsp; &nbsp; nearby_words.append(complete_word_list[found_word-1])&nbsp; &nbsp; &nbsp; &nbsp; nearby_words.append(complete_word_list[found_word+1])&nbsp; &nbsp; except (ValueError, IndexError):&nbsp; &nbsp; &nbsp; &nbsp; print('this is either not in the list of there was not an adjacent element on either side.')print(nearby_words)

MM们

使用enumerate,这样你就可以得到单词和相应的索引:for i, word in enumerate(complete_word_list):&nbsp; &nbsp; if word in dracula_list:&nbsp; &nbsp; &nbsp; &nbsp; if i:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nearby_words.append(complete_word_list[i-1])&nbsp; &nbsp; &nbsp; &nbsp; if i < len(complete_word_list) - 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nearby_words.append(complete_word_list[i+1])

qq_花开花谢_0

尝试这个:&nbsp;right= [ complete_word_list[complete_word_list.index(i)+1] for i in dracula_list if i in complete_word_list and complete_word_list.index(i)+1<len(complete_word_list)]&nbsp;left= [ complete_word_list[complete_word_list.index(i)-1] for i in dracula_list if i in complete_word_list and complete_word_list.index(i)-1>=0]&nbsp;nearby_words = left + right打印['train', 'anhour']
随时随地看视频慕课网APP

相关分类

Python
我要回答