简体   繁体   English

使用.append进行列表理解

[英]List comprehension using .append

There is probably so many problems with this code that can't be answered in a single post. 此代码可能有太多问题,无法在单个帖子中解决。 My main problem is I'm trying to lessen the amount of for loops with list comprehensions. 我的主要问题是我试图通过列表理解来减少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))

list comprehension isn't the only mprovement. 列表理解并不是唯一的改进。 Also get rid of for i in len(range(reqSoupElems)) antipattern by iterating directly on the elements: 还可以通过直接在元素上进行迭代来摆脱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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM