首页 > 解决方案 > 如何从两个字符串列表和一个条件中创建第三个列表?

问题描述

我有两个字符串列表。第一个列表包含所有英语单词。第二个包含大写字母(AZ)。我需要的是创建第三个不包含任何大写字母的列表。

例子:

words = ["Apple", "apple", "Juice", "tomato", "orange", "Blackberry"]

let = ["A", "B"]

第三个列表的结果应该是:

new_lst = ["apple", "Juice", "tomato", "orange"]

我尝试的只是不正确。我尝试过这样的事情。

new_lst = [ ]

for word in words:
    for l in let:
        if l not in word:
            new_lst.append(word)

print(new_lst)

我知道代码不正确,但显然我的大脑在一个多小时内没有找到任何解决方案,所以如果有人怜悯我......请帮我看看。

谢谢你。

标签: pythonstringlistconditional-statements

解决方案


事实上,你的条件对于 wordApple和 letter都会失败A,但是l = 'B'无论如何都会添加这个词(因为'B' not in "Apple")。

您可以all在此处使用以确保所有来自的字母let都不是in word

for word in words:
    if all(l not in word for l in let):
        new_lst.append(word)

或者简单地说:

for word in words:
    if word[0] not in let:
        new_lst.append(word)

可以写成列表理解:

new_lst = [word for word in words if word[0] not in let]

或者,您可以反转逻辑以删除元素而不是添加元素:

new_lst = words[:]  # create a copy of words

for word in words:
    for l in let:
        if l in word:
            new_lst.remove(word)
            break  # no need to check rest of the letters
print(new_lst)

或者:

new_lst = words[:]  # create a copy of words

for word in words:
    if word[0] in let:
        new_lst.remove(word)
print(new_lst)

推荐阅读