python中的For循环检查lis中的元素

2024-03-29 09:15:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

keys = ['well done','come on','going to','c','D','m','l','o']
values = ['well','going','come','D']
category = []
for index, i in enumerate(keys):
    for j in values:
        if j in i:
            category.append(j)
            break
        if index == len(category):
            category.append("other")
print(category)

我得到这个输出['well', 'other', 'come', 'going', 'other', 'D', 'other', 'other']

预期的输出是['well', 'come', 'going', 'other', 'D', 'other','other' 'other']

我不确定代码出了什么问题。你知道吗

任何帮助都将不胜感激。你知道吗


Tags: in密码forindexifonkeysvalues
2条回答

我会用一个标志来解决这个问题,如果它被发现的话,它会被标记出来。你知道吗

请记住,我在键的名称和值列表之间进行了切换,以使其更符合逻辑,并更改了“I”和“j”以使名称具有更好的含义。你知道吗

你可以保留你的名字,如果你想,只添加两行关于'找到'。你知道吗

values = ['well done', 'come on', 'going to', 'c', 'D', 'm', 'l', 'o']
keys = ['well', 'going', 'come', 'D']
category = []
for index, value in enumerate(values):
    found = False
    for key in keys:
        if key in value:
            category.append(key)
            found = True
            break
    if not found:
        category.append("other")
print(category)

方案2:

values = ['well done', 'come on', 'going to', 'c', 'D', 'm', 'l', 'o']
keys = ['well', 'going', 'come', 'D']
category = []
for index, value in enumerate(values):
    for key in keys:
        if key in value:
            category.append(key)
            break
    else:
        category.append("other")
print(category)

在我看来,选项2是解决问题的一种更优雅的方法。^在for之后的{}将被触发,以防for循环结束而没有击中途中的break。你知道吗

打印:['well', 'come', 'going', 'other', 'D', 'other', 'other', 'other']

关于你做错了什么-你在查看键列表而不是“值”列表时添加了“其他”。你知道吗

根据更新后的问题,很难判断每个关键元素的第一个单词是否是值中的单词。这个例子太宽泛了,所以我考虑到了这一点,并更新了我的答案。你知道吗

category = []
keys = ['start', 'steak well done', 'come on', 'He is going', 'c', 'D', 'm', 'l', 'o']
values = ['well', 'going', 'come', 'D']

for key in keys:
    if ' ' in key:
        for value in values:
            if value in key:
                category.append(value)
        continue
    if key in values:
        category.append (key)
        continue
    else:
        category.append ('other')

category
['other', 'well', 'come', 'going', 'other', 'D', 'other', 'other', 'other']

相关问题 更多 >