猿问

如果找不到与列表匹配的任何内容,如何附加到列表中?

当我的代码在整个列表中找不到任何内容时,我想打印。


这是我的代码:


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 中是否有第一个单词 - 如果有,那么我们用新的单词重放 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


千巷猫影
浏览 148回答 1
1回答

SMILET

您可能想查看 for-else:for item in items:&nbsp; &nbsp; if you_found_something:&nbsp; &nbsp; &nbsp; &nbsp; found_item = item&nbsp; &nbsp; &nbsp; &nbsp; breakelse:&nbsp; &nbsp; print('No item found.')&nbsp; &nbsp; do_your_append_here基本上 for-else 回答了 for 循环是否不间断地终止的问题。上面我们在发现某些东西时else会中断,因此不会执行,但只要您的 for 循环在没有 break 语句的情况下终止,则将else执行中的代码。
随时随地看视频慕课网APP

相关分类

Python
我要回答