简体   繁体   English

python-在函数中创建列表

[英]python - create list in function

I am trying to learn python and have the below script that works, but I want to use the results to create a list that I can call outside the function. 我正在尝试学习python并使用下面的脚本,但是我想使用结果创建一个可以在函数外部调用的列表。 When I print list the right results are produced. 当我打印清单时,将产生正确的结果。 The print x does nothing. print x不执行任何操作。

import requests
from bs4 import BeautifulSoup
import urllib
import re

def hits_one_spider():
    #page = 1
    #while page <= max_pages:
        url = "http://www.siriusxm.ca/hits-1-weekend-countdown/"
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for link in soup.find('div', {'class': 'entry-content'}).findAll('li'):
            #href = "http://www.siriusxm.ca/" + link.get('href')
            title = link.string
            #print(href)
            #print(title)
            return list

x = hits_one_spider()

print x

The problem is that you say return list in the for loop. 问题是您在for循环中说了return list Thus it returns after the first iteration. 因此,它在第一次迭代后返回。 Further you aren't actually returning it as a list, by doing it like that. 而且,通过这样做,您实际上并没有将其作为列表返回。

What you instead what is something like this: 相反,您的情况是这样的:

lst = []
for link in soup.find('div', {'class': 'entry-content'}).findAll('li'):
    lst.append(link.string)
return lst

Which results in returning (and printing) a list containing: 这将导致返回(并打印)包含以下内容的列表:

[
    "Sam Smith – Stay With Me",
    "Kongos – Come With Me Now",
    "Iggy Azalea – Fancy feat. Charli XCX",
    "OneRepublic – Love Runs Out",
    "Magic! – Rude",
    ... and a lot more ...
    "Oh Honey – Be Okay",
    "Katy Perry – Birthday",
    "Neon Trees – Sleeping With A Friend",
    "Cher Lloyd – Sirens",
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:创建一个函数来通过引用而不是值来修改列表 - Python: create a function to modify a list by reference not value Python - 从列表创建字典的函数 - Python - function to create a dictionary from a list python:是否可以在函数内创建一个列表? - python: Is it possible to create a list inside of a function? 如何在 Python 中创建 function 以确定列表是否已排序? - How to create a function in Python to determine if list is sorted or not? 如何为列表创建 function 到 output 范围(在 python 中) - How to create a function to output ranges for a list (in python) Python:从函数创建列表,返回单个项目或另一个列表 - Python: Create list from function that returns single item or another list 创建一个计算特定长度列表中的单词/字符串的函数-Python 3 - Create a function that counts words/strings in a list of a specific length - Python 3 如何在 Python 中创建一个接受数字和整数列表的函数? - How can I create a function in Python that takes a list of numbers and an integer? 在一个函数中创建列表,然后在python(pythonista ios)中的另一个函数中使用它 - Create list in one function, then use it in another in python (pythonista ios) Python 创建在回调 function 中存储新 ID 的列表 - Python create list that stores new ids inside a callback function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM