[英]How to make third list from two lists of strings and one condition?
我有兩個字符串列表。 第一個列表包含所有英語單詞。 第二個包含大寫字母 (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)
我知道不正確的代碼,但顯然我的大腦在一個多小時內沒有找到任何解決方案,所以如果有人憐憫我......請幫我看看。
謝謝你。
實際上,您的條件將失敗Apple
和字母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)
您可以使用set
的方法來處理該任務,如下所示:
words = ["Apple", "apple", "Juice", "tomato", "orange", "Blackberry"]
let = set(["A", "B"]) # equivalent to: let = set("AB")
new_lst = [i for i in words if let.isdisjoint(i)]
print(new_lst) # ['apple', 'Juice', 'tomato', 'orange']
請注意,我使用了set
let
,因此有方法isdisjoint
,它接受iterable ,因此不需要將參數隱式轉換為set
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.