[英]turning a loop into a list python
Below is my code: I am trying to turn the loop results I get from this code into a list. 下面是我的代码:我试图将从此代码中获得的循环结果转换为列表。 Any ideas?
有任何想法吗?
import requests
from bs4 import BeautifulSoup
page = requests.get('http://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168')
soup = BeautifulSoup(page.text, 'html.parser')
for x in soup.find_all(class_='tombstone-container'):
y = (x.get_text())
print (y)
if you don't want to change much of your code, create an empty list before your loop like this 如果您不想更改太多代码,请在循环之前创建一个空列表,如下所示
myList = []
and in your loop append the content like this: 并在循环中添加如下内容:
myList.append(str(x.get_text())) # EDIT2
EDIT1: The reason I used myList.append(...)
above instead of myList[len(myList)]
or something similar, is because you have to use the append method to extend already existing lists with new content. EDIT1:之所以使用上面的
myList.append(...)
而不是myList[len(myList)]
或类似的原因是因为您必须使用append方法来扩展具有新内容的现有列表。
EDIT2: Concerning your problem with None pointers in your list: If your list looks like [None, None, ...]
when printed after the for loop, you can be sure now that you have still a list of strings, and they contain the word None (like this ['None','None',...]
). EDIT2:关于列表中没有指针的问题:如果在for循环后打印时列表看起来像
[None, None, ...]
,则现在可以确定您仍然有字符串列表,并且它们包含单词None(例如['None','None',...]
)。 This would mean, that your x.get_text()
method returned no string, but a None-pointer from the beginning. 这意味着您的
x.get_text()
方法从一开始就不返回任何字符串,而是返回一个无指针。 In other words your error would lie buried somewhere else. 换句话说,您的错误将隐藏在其他地方。
Just in case. 以防万一。 A complete example would be:
一个完整的例子是:
myList = []
for x in soup.find_all(class_='tombstone-container'):
# do stuff, but make sure the content of x isn't modified
myList.append(str(x.get_text()))
# do stuff
只是循环。
map(lambda x: x.get_text(), soup.find_all(class_='tombstone-container'))
A straightforward way to convert the results of a for
loop into a list is list comprehension . 将
for
循环的结果转换为列表的一种直接方法是列表理解 。
We can convert: 我们可以转换:
for x in soup.find_all(class_='tombstone-container'):
y = (x.get_text())
print (y)
into: 变成:
result = [x.get_text() for x in soup.find_all(class_='tombstone-container')]
Basic (list comprehension has a more advanced syntax) has as grammar: 基本(列表理解具有更高级的语法)具有以下语法:
[<expr> for <var> in <iterable>]
it constructs a list where Python will iterate over the <iterable>
and assigns values to <var>
it adds for every <var> in <iterable>
the outcome of <expr>
to the list. 它构造了一个列表,Python将在该列表上迭代
<iterable>
并将值赋给<var>
它为<var> in <iterable>
的每个<var> in <iterable>
添加<expr>
的结果到列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.