我遇到了我的代码问题,一旦从列表列表中删除列表,循环就会停止运行。
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']]
如何让循环继续到列表末尾?
答案 0 :(得分:4)
那是因为,当您删除第二个项目(其索引为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)
答案 1 :(得分:2)
记住
data = [["list", "in","a list"],["list", "in","a list"],["list", "in","a list"]]
#data[0] will return ["list", "in","a list"]
#data[0][0] will return "list"
#remember that lists starts with '0' -> data[0]
答案 2 :(得分:1)
>>> data=[["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]]
>>> y = []
>>> for subData in data:
for dataItem in subData:
if dataItem == "hello":
y.append(subData)
>>> y
[['why', 'why', 'hello'], ['why', 'cry', 'hello']]
答案 3 :(得分:1)
rand()
OR
filter(lambda x : x[-1] =="hello",[["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]])
OR
reduce(lambda x,y : x + [y] if y[-1]=="hello" else x ,[["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]],[])
答案 4 :(得分:1)
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)
不要迭代原始数据,而是复制(data [:])。因为从列表中删除项目时,项目的索引将发生变化。列表索引中的["why","why","bell"]
是1.从数据中删除时。数据索引中的["why","hi","sllo"]
将为1.下一个迭代索引为2,因此传递["why","hi","sllo"]
并检查["why","cry","hello"]
。