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

2024-04-20 11:40:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我(一个新手)试图迭代一个长列表,但是我写的函数不会迭代整个列表,为什么?你知道吗

这是一个程序,将采取的名单输入和搜索谷歌寻找相关的网站,并返回这些网站的链接,我在一个列表的形式。使用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']}

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


Tags: infromimportcom列表fordefitem
2条回答

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

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

那就行了。对于您的答案,因为循环中的最后一项作为元组返回,并且在第for i, next_item in w_next(args):行中解包。在i上调用函数,但最后一项在next_item中,永远不会处理。你知道吗

>>> 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中有一个off by one错误。列表中的最后一项永远不会出现。整个事情可以变得简单得多:

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

注意,为了简单起见,我用print替换了您的yield。你知道吗

相关问题 更多 >