python - 从 Python 2.7 中的列表中删除特定项目

标签 python

我目前正在尝试弄清楚如何循环遍历我拥有的列表,并根据列表中是否包含特定单词来消除该列表中的某些项目。

这是我到目前为止的代码:

for container in containers:
    days = container.findAll('p',{'class':'period-name'})
    #Assigns all of the classes of the day names to days
    for day_descriptor in days:
        day = day_descriptor.text
        #loops through days classes and stores those each of those in a day
    forecasts = container.findAll('p',{'class':'short-desc'})
    for forecast_descriptor in forecasts:
        forecast = forecast_descriptor.text
        #loops through forecasts classes and stores those each of those in a forecast
    print(day)

列表日期显示为:

day = ['Tonight', 'Friday', 'FridayNight', 'Saturday', 'SaturdayNight', 'Sunday', 'SundayNight', 'Monday', 'MondayNight']

但是,我不希望任何包含“Night”一词的项目(如果该词是“Tonight”则除外)包含在该列表中。我该如何去做呢?

最佳答案

如果我按原样获取数据,那么当 Night 与星期几复合且 N 大写时,我可以通过过滤掉包含 Night 的条目来将其与 Tonight 分开处理。

例如,这是一个列表理解解决方案:

>>> days = ['Tonight', 'Friday', 'FridayNight', 'Saturday', 'SaturdayNight', 'Sunday', 'SundayNight', 'Monday', 'MondayNight']
>>> new_days = [day for day in days if 'Night' not in day]

但是如果您想打破它,您可以简单地这样做:

corrected_days = []
for day in days:
    if 'Night' not in day:
        corrected_days.append(day)

关于python - 从 Python 2.7 中的列表中删除特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53879382/

相关文章:

python - 为什么 selenium webdriver 找不到我的元素

python - 如何根据Python中行值的条件应用列中的值

python - 如何让 python 信任我服务器的 TLS 自签名证书 : ssl. SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败

python - 根据现有列的条件语句向 pandas 数据框添加新列

python - 如何让scrapy爬虫不以指数方式聚合结果

python - 使用 altair 制作仪表板

python - 在不使用字典的情况下用另一个列表的项目替换列表中的项目

python - Mongodb 默认在插入时使用当前时间戳

python - 100 步 100 名随机游走者的平均值

python - 如何在 Python < 3 中将 UTF-8 编码的文本打印到控制台?