我目前正在尝试弄清楚如何循环遍历我拥有的列表,并根据列表中是否包含特定单词来消除该列表中的某些项目。
这是我到目前为止的代码:
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/