如何处理 'NoneType' 对象不可迭代

How to handle 'NoneType' object is not iterable

我的代码在几天前一直在工作,但从今天开始就停止工作了。 该问题与 itertools 的组合任务相关,如下所示:

from itertools import combinations


def combinations(items):
    result = []
    for i in range(1, len(items) + 1):
        result.extend(itertools.combinations(items, i)) 
    page_text = page_text.css('.rcl-ParticipantFixtureDetails_LhsContainerInner')

    for match in page_text:
        teams = match.css('.rcl-ParticipantFixtureDetailsTeam_TeamName ::text').getall()
        times = match.css('.rcl-ParticipantFixtureDetails_BookCloses ::text').getall()
        row = {
            "Home": teams[0], 
            "Away": teams[1],
            "Time": times
        }
        rows.append(row)

df = pd.DataFrame(rows)
data = []
for i, (home, away, time) in enumerate(df[['Home', 'Away', 'Time']].values):
    home_words, away_words = home.split(), away.split()
    for home_combo in combinations(home_words):
        for away_combo in combinations(away_words):
            if home_combo and away_combo:
                data.append([i, home, away, time, f'{" ".join(home_combo)} - {" ".join(away_combo)}'])

这是错误

     97 for i, (home, away, time) in enumerate(df[['Home', 'Away', 'Time']].values):
     98     home_words, away_words = home.split(), away.split()
---> 99     for home_combo in combinations(home_words):
    100         for away_combo in combinations(away_words):
    101             if home_combo and away_combo:

TypeError: 'NoneType' object is not iterable

问题出在这里:

from itertools import combinations

def combinations(items):
    ...

您的 combinations 函数屏蔽了您从 itertools 导入的 combinations,因此您只是调用自己的函数,这隐式 returns None .只需将您的函数重命名为其他名称,您就可以引用所需的导入函数。

您正在 for 循环中调用一个函数,该函数目前 return 没有执行任何操作。您可以将 return 语句添加到您的函数并将其传递给您的循环。请记住,由函数编辑的值 return 应该是可迭代的,例如列表、元组、字典、字典等