浏览时我想删除或添加列表元素,但IndexError:列表索引超出范围
listStep = ['0', '0', '0', '1', '1', '1', '3', '1', '3', '0']
for i in range(0, len(listStep) - 2, 2):
for j in range(i + 2, len(listStep), 2):
if listStep[i + 1] == listStep[j + 1]:
listStep[i] = listStep[i] + listStep[j]
listStep.pop(j)
listStep.pop(j)
print(listStep)
所需的输出:
['03', '0', '013', '1']
答案 0 :(得分:0)
所有建议都不要突变您要遍历的列表,因为很难推断出您所做的事情。而不是使用[:]
遍历列表的副本。
答案 1 :(得分:0)
典型的off by one error,因为数组索引从0开始到version: "2"
services:
www:
build: .
container_name: Web
ports:
- "80:80"
restart: always
command: tail -f /dev/null
volumes:
- .:/var/www/html
- /var/run/docker.sock:/var/run/docker.sock
networks:
internal:
shared:
ipv4_address: 172.55.0.5
ubuntu:
build:
context: ./dockerFiles/ubuntu
container_name: Radius
ports:
- "5000:5000"
volumes:
- ./dockerFiles/radius/ubuntu:/ubuntu
restart: always
networks:
internal:
shared:
ipv4_address: 172.55.0.4
volumes:
persistent:
networks:
internal:
driver_opts:
internal: "true"
driver: bridge
shared:
driver_opts:
enable_ipv6: "true"
driver: bridge
ipam:
config:
- subnet: 172.55.0.0/16
gateway: 172.55.0.1
结束。即length - 1
的{{1}}(listStep[i + 1]]
的最后一个值)是i == len(listStep) - 1
,即您正在访问列表末尾的一个元素。
您还在处理列表时对其进行修改,以便range()
更改其值。