python-3.x - 如何有条件地更新以前的迭代器附加值?
问题描述
我有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
列表项的性质(它是一个后缀,这是我正在利用的语音功能的一部分),我认为它不会成为列表中的第一个条目。
如果/当出现问题时,我本来希望代码会中断,但我什至无法让它运行。
感谢你们对我的帮助!
解决方案
这应该这样做。
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']]
推荐阅读
- c# - 如何让 Chrome 进入前台?
- angular - 为什么当我打开 Angular Ivy 时我的指令不再起作用?
- r - 如何使用 r 识别配对交易
- x86 - 为什么 32 位 .MSI 文件的 ProductCode 与注册表中的对应文件不同?
- r - 使用ggplot2在条形图上绘制线图
- next.js - 一旦NextJs已经触发过一次,如何避免触发getServerSideProps?
- python - pybind11 模块目录
- mysql - 查询很慢,我可以做些什么来改进?
- rest - 用于身份验证的 REST API URL 的最佳实践
- javascript - 虽然我在数组中的二进制搜索算法中的条件