如何迭代列表而不将新单词插入列表?

时间:2016-11-19 12:54:19

标签: list python-3.x loops iteration

我理解如何索引给定列表中的单词,但如果给定一个列表和一个不在列表中的单词,如何找到新单词的索引位置而不添加或插入新单词到排序列出?

例如: def find_insert_position:     a_list = ['鸟','狗','鳄鱼']     new_animal ='牛'

如果不改变列表,我如何确定在排序列表中插入新单词的位置?因此,如果您输入新单词,则列表将按字母顺序进行统计。请记住,这是一个给定的列表和单词,所以我不会事先知道任何单词。我正在使用Python3。

2 个答案:

答案 0 :(得分:0)

将变量计数器设置为0 循环遍历单词列表中的每个项目,并将列表中的每个单词与给定列表进行比较 如果给定的单词大于列表中的项目,则递增计数器

因此,当您不在循环中时,计数器值就是您要查找的索引。

您可以将其转换为代码。

答案 1 :(得分:0)

如果可以在不改变原始列表的情况下将单词添加到另一个 ,则可以尝试:

def find_insert_position(lst, word):
    new_lst = lst[:]    # make a copy of the list so you don't modify the original
    new_lst.append(word)    # add word to lst
    sorted_lst = sorted(new_lst) 
    return sorted_lst.index(word)    # return 0-based position of word in  sorted list

a_list = ['Bird', 'Dog', 'Alligator']
new_animal = 'Cow'

print(find_insert_position(a_list, new_animal))
相关问题