如何解决如何在for循环中为if语句分配变量?
我想在一行中加入 for循环和if语句。
扩展代码:
for item in number:
if item['datetime'] not in number:
print('Not there')
我尝试过:
eg = [if item['datetime'] not in number: print('Not there') for item in number]
代码:
req = requests.get(url2 + str(page))
soup = BeautifulSoup(req.content,'html.parser')
g_data = soup1.find_all('span',{"class": "b-card b-card-mod-hvehicle"})
g_price = soup.find_all('div',{"class": "b-card--el-vehicle-price"})
g_mile = soup.find_all('p',{"class": "b-card--el-brief-details"})
g_name = soup.find_all('p',{"class": "b-card--el-description"})
g_user = soup.find_all('a',{"class": "b-card--el-agency-title"})
g_link = soup.find_all('div',{"class": "b-card--el-inner-wrapper"})
g_sales = soup.find_all('span',{"class": "b-card--el-featured-label"})
time = soup.find_all('time',{"class":"timeago b-card--el-agency-time"})
m_price = [item.text for item in g_price]
m_mile = [item.text for item in g_mile]
m_user = [item.text for item in g_user]
m_name = [item.text for item in g_name]
m_link = [item.a["href"] for item in g_link]
m_extensions = [('') for item in g_link]
m_sales = [item.text for item in g_sales]
r_time = [dateutil.parser.parse(item['datetime']).strftime('%m-%d-%Y:%H:%M:%s') for item in time]
req2 = requests.get(m_extension + m_link)
soup_req2 = BeautifulSoup(req2.content,'html.parser')
number = soup_req2.find_all('a',{"class": "b-seller--el-show-contacts b-line-mod-thin"})
test1 = (if item['mobile'] not in item: item = ('Sold') for item in number)
给我一个语法错误。 谢谢!
解决方法
您的示例存在矛盾-> item in number
,但您也有item['datetime'] not in number
我会举个例子:
numbers = [1,2,3,4,5,6,7,8,9,10]
列出偶数:
evenNo = [x for x in numbers if x%2==0]
类似于上面,但是只打印偶数而不是列出:
printEven = [print(x) for x in numbers if x%2==0]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。