我有list
的{{1}}:
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
时合并一个值。
所需的输出是这样:
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)
列表项的性质(这是一个后缀,这是我正在利用的语音功能的一部分),我认为它不会成为列表中的第一项。
如果发生问题,我本希望代码会中断,但是我什至无法运行它。
谢谢您的帮助!
答案 0 :(得分:0)
这应该做到。
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']]