[英]Eliminating specific items from a list in Python 2.7
我目前正在嘗試找出如何遍歷我擁有的列表,並根據它們中是否包含特定單詞來消除列表中的某些項目。
到目前為止,這是我的代碼:
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”,則不包括在內)。 我將如何去做?
如果我按原樣獲取數據,那么當“夜晚”與星期幾混合,並且將N大寫時,則可以通過過濾掉包含“夜晚”的條目,將其與“夜晚”分開處理。
例如,這是一個列表理解解決方案:
>>> 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)
您可以使用in
檢查文本中是否存在夜晚。
例如: 假設day_descriptor.text是文本而不是列表
if 'night' not in day_descriptor.text:
day.append( day_descriptor.text)
或者從當天開始,您只能選擇必要的內容。
[d for d in day if not 'Night' in d]
我喜歡endswith
了in
:
day = [name for name in day
if not name.endswith('Night')]
如果必須不區分大小寫:
day = [name for name in day
if not name.lower().endswith('night') or name.lower() == 'tonight']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.