我(一个新手)试图迭代一个长列表,但是我写的函数不会迭代整个列表,为什么?你知道吗
这是一个程序,将采取的名单输入和搜索谷歌寻找相关的网站,并返回这些网站的链接,我在一个列表的形式。使用Python 3
import logging
import os
import pandas as pd
import re
import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from googlesearch import search
def get_urls(tag, n, language):
urls = [url for url in search(tag, stop=n, lang=language)][:n]
return urls
my_list = [['Apples'], ['Oranges'], ['Pears']]
flat_list = []
for sublist in my_list:
for item in sublist:
flat_list.append(item)
i = 0
sizeofList = len(flat_list)
while i < sizeofList:
print(flat_list[i])
i+=1
def w_next(iterable):
iterator = iter(iterable)
current = next(iterator)
for next_item in iterator:
yield current, next_item
current = next_item
myResults=[]
def look(*args):
for i, next_item in w_next(args):
if sizeofList > 0:
myResults.append(get_urls(i, 2, 'en'))
else:
return "".join(myResults)
print (myResults)
look(*flat_list)
实际输出:
[['apples.com', 'yummyapples.com'], ['oranges.com', 'yummyoranges.com']]
预期产量:
[['apples.com', 'yummyapples.com'], ['oranges.com', 'yummyoranges.com'], ['pears.com', 'yummypears.com']}
我只是想让它遍历整个列表,但为什么不呢?你知道吗
为什么在你的
w_next
中需要next_item
?简单地做那就行了。对于您的答案,因为循环中的最后一项作为元组返回,并且在第
for i, next_item in w_next(args):
行中解包。在i
上调用函数,但最后一项在next_item
中,永远不会处理。你知道吗在
w_next
中有一个off by one错误。列表中的最后一项永远不会出现。整个事情可以变得简单得多:注意,为了简单起见,我用
print
替换了您的yield
。你知道吗相关问题 更多 >
编程相关推荐