作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的代码遇到一个问题,一旦从列表列表中删除列表,循环就会停止运行。
data=[["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]]
for word_set in data:
if word_set[-1]!="hello":
data.remove(word_set)
print(data)
我想要的输出是
[['why', 'why', 'hello'], ['why', 'cry', 'hello']]
但是输出是
[['why', 'why', 'hello'], ['why', 'hi', 'sllo'], ['why', 'cry', 'hello']]
如何让循环一直持续到列表末尾?
最佳答案
这是因为,当您删除第二个项目(其索引为 1)时,它之后的项目会向前移动。在下一次迭代中,索引为 2。它应该指向 ["why","hi","solo"]
。但由于项目向前移动,它指向 ["why","cry","hello"]
。这就是您得到错误结果的原因。
不建议在遍历列表时删除列表项。
您可以创建一个新列表(在第一个答案中提到)或使用 filter
函数。
def filter_func(item):
if item[-1] != "hello":
return False
return True
new_list = filter(filter_func, old_list)
关于python - 遍历列表python的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33865029/
我是一名优秀的程序员,十分优秀!