繁体   English   中英

为什么我的列表特别是列表的最后一项没有遍历迭代(或在输出中看不到)?

[英]Why is my list specifically the last item of the list not going through the iteration (or not seen in output)?

我(Newb)试图遍历一个长列表,但是我编写的函数不会遍历整个列表,为什么?

这是一个程序,它将使用列表输入并搜索google以查找相关网站,并以列表形式将这些网站链接返回给我。 使用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']}

我只是想让它遍历整个列表,但是为什么不呢?

>>> def w_next(iterable):
...     iterator = iter(iterable)
...     current = next(iterator)
...     for next_item in iterator:
...         print(current, next_item)
...         current = next_item
... 
>>> w_next(['apple', 'pear', 'orange'])
apple pear
pear orange

您在w_next一个错误的错误。 列表中的最后一项将永远不会显示。 整个事情可以变得容易得多:

>>> def w_next(my_list):
...     for item in my_list:
...         print(item)
... 
>>> w_next(['apple', 'pear', 'orange'])
apple
pear
orange
>>> 

请注意,为简单起见,我用print代替了您的yield

为什么在next_item中需要w_next 简单地做

>>> def w_next(iterable):
...     iterator = iter(iterable)
...     for current in iterator:
...         yield current

这样就可以了。 对于您的答案,由于循环中的最后一项作为元组返回,并在for i, next_item in w_next(args):行中解压缩for i, next_item in w_next(args): 您在i上调用了函数,但是最后一项在next_item ,并且从未处理过。

暂无
暂无

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

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