首页 > 解决方案 > 如何有条件地更新以前的迭代器附加值?

问题描述

我有list一个lists

   my_list_of_lists =  [['a', 'keep me alone'],
                        ['b', 'keep me alone'],
                        ['c', 'Put me with previous value'],
                         ['d', 'keep me alone']]

我想循环my_list_of_lists并组合一个值 when 前一个值 when my_list[1] == 'Put me with previous value'

所需的输出是这样的:

my_updated_list_of_lists = [['a', 'keep me alone'], ['bc', 'keep me alone'], ['d', 'keep me alone']]

我尝试了以下代码,但不断收到IndexError: list index out of range错误消息:

n = 0
my_updated_list_of_lists = []
for my_list in my_list_of_lists:
    n = n+1
    if my_list[1] == 'Put me with previous value':
        my_updated_list_of_lists[n-1][0] = my_updated_list_of_lists[n-1][0] + my_list[0]
        continue 
    else:
        my_updated_list_of_lists.append(my_list)

由于Put me with a previous value列表项的性质(它是一个后缀,这是我正在利用的语音功能的一部分),我认为它不会成为列表中的第一个条目。

如果/当出现问题时,我本来希望代码会中断,但我什至无法让它运行。

感谢你们对我的帮助!

标签: python-3.xlistloops

解决方案


这应该这样做。

my_list_of_lists = [['a', 'keep me alone'],
                    ['b', 'keep me alone'],
                    ['c', 'Put me with previous value'],
                    ['d', 'keep me alone']]

my_updated_list_of_lists = []

for i in range(0, len(my_list_of_lists)):

    elem = my_list_of_lists[i]

    #Merge the first element of 2 consecutive items if second item contains Put me with previous value
    if i+1 < len(my_list_of_lists) and my_list_of_lists[i+1][1] == 'Put me with previous value':
        elem[0] = elem[0]+my_list_of_lists[i+1][0]
    #Ignore element containing Put me with previous value
    elif elem[1] == 'Put me with previous value':
        continue
    #Append element to new list
    my_updated_list_of_lists.append(elem)

print(my_updated_list_of_lists)
#[['a', 'keep me alone'], ['bc', 'keep me alone'], ['d', 'keep me alone']]

推荐阅读