简体   繁体   中英

How to assign a variable to an if statement in a for loop?

I would like to have my for loop and if statement in a line .

Expanded Code:

for  item in number:
    if item['datetime'] not in number:
        print('Not there')

I tried this:

eg = [if item['datetime'] not in number: print('Not there') for item in number]

Code:

                    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)

Gives me a syntax error. Thanks!

Your example has a contradiction --> item in number but you also have item['datetime'] not in number

I'll try put an example:

numbers = [1,2,3,4,5,6,7,8,9,10]

To make list of even numbers:

evenNo = [x for x in numbers if x%2==0]

Similar to above, but just print the even numbers instead of putting a list:

printEven = [print(x) for x in numbers if x%2==0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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