在Python中初始化列表的第一个索引 [英] Initialize the first index of a list in Python
本文介绍了在Python中初始化列表的第一个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将用C ++编写的内容转换为Python.这是我要用python重写的代码片段:
I am converting something I wrote in C++ to Python. Here is a snippet of what I am trying to rewrite in python:
std::vector<int> dates(numberOfPayments.size(), 0);
dates[0] = NDD[0] - '0';
for (int i = 1; i < dates.size(); ++i)
{
dates[i] = (dates[i - 1] + 12 - numberOfPayments[i - 1]) % 12;
}
我遇到的问题是我无法将python中列表的第一个索引设置为某些值.我尝试这个:
The problem I am having is that I cannot set the first index of my list in python to something. I try this:
dates = []
dates[0] = NDD_month[0]
for i in range(len(first_payments)):
dates[i] = (dates[i-1] + 12 - first_payments[i-1]) % 12
print(dates)
但是我得到这个错误:
IndexError: list assignment index out of range
有人知道如何解决这个问题吗?
Anyone know how to fix this?
推荐答案
您遇到了此问题,因为您试图访问尚未分配的索引.
You're having this problem because you're trying to access a index that was not allocated yet.
要将内容附加到列表中,应使用append
(已修改以修复循环):
To append things to a list you should use append
(edited to fix loop):
dates = []
dates.append(NDD_month[0])
for i in range(1, len(first_payments)):
dates.append((dates[i-1] + 12 - first_payments[i-1]) % 12)
print(dates)
这篇关于在Python中初始化列表的第一个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文