当我的代码在整个列表中找不到任何内容时,我想进行打印。
这是我的代码:
new_list = ['There%is', 'None&of', 'Same&here']
a = new_list.split("%")
old_list = ['Stack%Hello', 'Over&You', 'flow&There']
condition = True
while condition:
try:
for i, items in zip(range(len(old_list)), old_list):
old_list_value = old_list[i].split("%")
if a[0] in items:
if len(old_list_value[1]) < len(a[1]):
old_list[i] = new_list
condition = False
elif len(old_list_value[1]) > len(a[1]):
old_list[i] = new_lis
condition = False
else:
old_list.append(new_list)
condition = False
break
except Exception as err:
print(err)
我想做的是:检查每个 % 的每个第一个单词,然后我从 old_list 进行比较以检查 old_list 中是否有第一个单词 - 如果有则我们重播它是旧列表值和新值。
elif 如果单词比 new_list 单词长那么我们什么都不做。
如果在整个列表中找不到 if a[0] in items:,我该如何做,那么我们基本上将 new_list 添加到 old_list 中?
这意味着它需要首先搜索所有单词,如果它包含在 old_list 中,如果不是,那么我们追加。
新编辑:
代码:
new_list = ['There%is', 'None&of', 'Same&here']
a = new_list.split("%")
old_list = ['Stack%Hello', 'Over&You', 'flow&There']
for i, items in zip(range(len(old_list)), old_list):
old_list_value = old_list[i].split("%")
if a[0] in items:
if len(old_list_value[1]) < len(a[1]):
old_list[i] = new_list
break
elif len(old_list_value[1]) > len(a[1]):
old_list[i] = new_list
break
else:
old_list.append(new_list)
break
请您参考如下方法:
你可能想看看 for-else:
for item in items:
if you_found_something:
found_item = item
break
else:
print('No item found.')
do_your_append_here
基本上,如果 for 循环没有间断地终止,for-else 就回答了这个问题。上面我们在找到某些东西时中断,因此 else 将不会被执行,但是只要你的 for 循环在没有 break 语句的情况下终止,那么 else 中的代码将被执行.
