我有以下代码,我打电话给程序写:
python new.py -s 13 -p 5
但是,在第63行,我收到以下错误。我知道这意味着什么,但我不能理解为什么。
Traceback (most recent call last):
File "new.py", line 63, in <module>
rythm[i].append(rythm[last])
IndexError: list index out of range
还有代码。我想要做的是在1s中平均分配0。第一个输入是0s和1s的字符串长度,第二个输入是1s的numper。谢谢!
import argparse
p = argparse.ArgumentParser()
p.add_argument("-pulses", help = "number of pulses", type = int)
p.add_argument("-slots", help = "length of the rythm", type = int)
args = p.parse_args()
slots = args.slots
pulses = args.pulses
pauses = slots - pulses
mod = pauses % pulses
rythm = []
if mod == 0:
x = slots/pauses
l = 0
while l<slots:
if l%x == 0:
rythm.append(1)
else:
rythm.append(0)
l = l + 1
print (rythm)
if mod != 0:
i = 0
j = 0
while i < pulses:
rythm.append([1])
i = i + 1
while j < pauses:
rythm.append([0])
j = j + 1
last = len(rythm)
last = last - 1
last_len = len(rythm[last])
x = slots%pauses
y = pauses - x
flag = True
while flag == True:
flag = False
if (last_len != 1) or (rythm[last] != 0):
flag = True
i = 0
while i < x:
rythm[i].append(rythm[last])
rythm.remove(rythm[last])
i = i + 1
y = y - x
x = x%y
last = len(rythm)
last = last - 1
last_len = len(rythm[last])
print (rythm)
答案 0 :(得分:0)
IndexError: list index out of range
- 表示您正在按位置访问不存在的值。
例如:
a = range(10) #length of a is 9, list indices start at 0
print(a[10]) #accessing value by a index that doesn't exist, raises a IndexError exception
答案 1 :(得分:0)
请在这里查看:
if (last_len != 1) or (rythm[last] != 0):
是:
if (last_len != 1) or (rythm[last] != [0]):
添加一些调试或简单的打印语句。当你尝试这个:
rythm[i].append(rythm[last])
rythm[last]
肯定没有,因为你做了
rythm.remove(rythm[last])
在最后一次迭代中。