python - 如何从两个字符串列表和一个条件中创建第三个列表?
问题描述
我有两个字符串列表。第一个列表包含所有英语单词。第二个包含大写字母(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)
我知道代码不正确,但显然我的大脑在一个多小时内没有找到任何解决方案,所以如果有人怜悯我......请帮我看看。
谢谢你。
解决方案
事实上,你的条件对于 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)
推荐阅读
- php - 如何在 ERD 图中实现“可以”关系?
- python - 熊猫如何检查列值之间的差异是否在每个组中的范围内
- ruby-on-rails - 在 RoR 中创建 CKAN 资源,以字符串形式提供文件内容
- javascript - 停止冒泡时会先调用哪个事件?
- python - 如果值计数低于阈值,则将列值映射到“杂项” - 分类列 - Pandas Dataframe
- asp.net-core-2.0 - Abp Castle 依赖注入抽象类
- angular - 使用 Angular 6 项目安装 Webpack 时出错
- javascript - 使用 lodash 在 JavaScript 中对多行数据进行排序
- node.js - 我们如何让代码等待在 node.js 中执行下一条语句
- c# - 避免掉边