【发布时间】:2021-12-28 21:30:31
【问题描述】:
sentence = [[1,0,3],[2,0,0],[0,0,5]]
empty = []
for element in sentence :
for icelement in element :
if not icelement == 0:
empty.append(icelement)
print(empty)
print(empty[2]) #this should give 3 or empty[8] should give 5
我做了很多尝试,但仍然有问题。我知道这是因为 python 自动更新元素索引但不知道如何控制它。任何建议都会对我有所帮助。
num = [1,0,4,5]
print(num[3]) #gives 5
for n in num :
if n == 0:
num.remove(n)
print(num[3])# doesnt exist.
【问题讨论】:
-
不清楚你想要什么。为什么
empty[2]会是3或者为什么empty甚至有9 个元素让你能够做到empty[8]?请提供预期的输出以及它是如何形成的。 -
嘿,@Bünyamin Mete,Python 索引从 0 开始。所以如果你想打印 number 3 你需要使用索引 1,像这样:
print(empty[1]) -
您能否添加更多信息,您期望的输出是什么,您是否试图收集所有不为零的元素?您要存储什么索引。您当前的输出应该类似于 [1,3,2,5],您是否期望相同?
-
你只是想扁平化数组吗?
-
顺便说一句,使用
if not x == 0:有点奇怪,对于“不等于”,您通常会使用if x != 0:
标签: python arrays python-3.x list