[英]List comprehension using .append
此代碼可能有太多問題,無法在單個帖子中解決。 我的主要問題是我試圖通過列表理解來減少for循環的數量。
# import required libraries
import bs4, requests, re
# Get the HTML and store it in req variable
req = requests.get('Website')
# Make a BS object to help search HTML
reqSoup = bs4.BeautifulSoup(req.text, 'lxml')
# Search the ATIS under the 'pre' label and store it in reqSoupElems
reqSoupElems = reqSoup.select('pre')
# Create Regex's to search the ATIS
timeRegex = re.compile(r'\d\d\d\d\d\d')
WXRegex = re.compile(r'WX:\s.*')
# Create empty lists to store the data extracted for the ATIS
time = []
WX = []
# Create list with strings of time and weather elements extracted from ATIS
for i in range(len(reqSoupElems)):
# Create time list
time.append(timeRegex.search(str(reqSoupElems[i])).group())
# If the wx group isn't in ATIS append "Nill WX" to WX list
# Otherwise, append the weather in ATIS to WX list
if WXRegex.findall(str(reqSoupElems[i])) == []:
WX.append('Nil WX')
else:
WX.append(WXRegex.search(str(reqSoupElems[i])).group())
# Remove "WX: " from the strings within the lists
for i in range(len(WX)):
if WX[i][0:4] == 'WX: ':
WX[i] = WX[i][4:]
# Print to ensure it has worked
print('\n')
print(time)
print(len(time))
print('\n')
print(WX)
print(len(WX))
列表理解並不是唯一的改進。 還可以通過直接在元素上進行迭代來擺脫for i in len(range(reqSoupElems))
反模式中for i in len(range(reqSoupElems))
:
time = [timeRegex.search(str(element)).group() for element in reqSoupElems]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.