我想检查某项(此处return
)是否在mylist
的子列表中,然后将其追加到myOtherlist
,否则只需追加原始的{{1 }}到mylist
myOtherlist
在for循环中,该子列表正在更改,因此可能是子列表中mylist
项不存在的情况。
这里是一种情况:
输入
return
mylist = [['graph', 'destination'], ['modify', 'destination'], ['modify', 'destination'], ['return', 'modify']]
我的代码:
myOtherlist = []
预期输出:
for item in mylist:
if "return" in item:
myOtherlist.append(item)
else:
myOtherlist.append(mylist)
答案 0 :(得分:1)
删除else
语句:
mylist = [['graph', 'destination'], ['modify', 'destination'], ['modify', 'destination'], ['return', 'modify']]
myOtherlist = []
for item in mylist:
if "return" in item:
myOtherlist.append(item)
myOtherlist = myOtherlist or mylist
或list
理解:
myOtherlist = [item for item in mylist if "return" in item] or mylist
答案 1 :(得分:0)
尝试一下,看看它是否满足您的要求。但是我无法确切地说出您要执行的操作。
word_found = False
myList = ["return", "and", "other", "words"]
myOtherList = []
for word in myList:
if word == "return":
myOtherList.append(word)
global word_found = True
if word_found == False:
myOtherList.append(myList)
为了使它真正有用,您需要在函数中使用它,例如:
def Search(list1, list2, string): #Searches list 1 for a string and if found, adds it to list 2. Otherwise adds all of list 1 to list 2.
word_found = False
for word in list1:
if word == string:
list2.append(word)
global word_found = True
if word_found == False:
list2.append(list1)
而且,出于好奇,以您提供的示例为例,字典是否会使它变得更简单?