获取值并追加到列表,然后追加到另一个列表

时间:2018-10-08 21:56:44

标签: python

所以我要使用BS4进行报废,我想将值的每一行都放在不同的列表中,然后将所有这些列表合并到一个列表中。

目前我正在这样做:

team_values = []
teams_values = []
for team in team_rows:
    team_data = team.find_all("td")

    for data in team_data:
        if hasattr(data, 'attrs') and 'data-val' in data.attrs:
            #print("\t{}".format(data.attrs['data-val']))
            value = data.attrs['data-val']
            #print(value)
            team_values.append(value)
            #print(team_values)
teams_values.append(team_values)

但是它将返回一个值列表,而不是列表列表。有什么帮助吗?

4 个答案:

答案 0 :(得分:1)

您的缩进在最后一行关闭,您需要在进入第二个team_values循环之前重置for

teams_values = []
for team in team_rows:
    team_data = team.find_all("td")

    team_values = []                 # reset here  
    for data in team_data:
        if hasattr(data, 'attrs') and 'data-val' in data.attrs:
            #print("\t{}".format(data.attrs['data-val']))
            value = data.attrs['data-val']
            #print(value)
            team_values.append(value)
            #print(team_values)
    teams_values.append(team_values)        # add indentation here

答案 1 :(得分:1)

尝试一下

teams_values = []
for team in team_rows:
    team_values = []
    team_data = team.find_all("td")

    for data in team_data:
        if hasattr(data, 'attrs') and 'data-val' in data.attrs:
            #print("\t{}".format(data.attrs['data-val']))
            value = data.attrs['data-val']
            #print(value)
            team_values.append(value)
            #print(team_values)
    teams_values.append(team_values)

在将team_values的内容附加到teams_values后,您并没有“重置”该内容。

PS:在我发布此答案时,其他两个都没有指出此“重置”。

答案 2 :(得分:1)

teams_values = []
for team in team_rows:
    team_data = team.find_all("td")
    team_values = []
    for data in team_data:
        if hasattr(data, 'attrs') and 'data-val' in data.attrs:
            #print("\t{}".format(data.attrs['data-val']))
            value = data.attrs['data-val']
            #print(value)
            team_values.append(value)
            #print(team_values)
    teams_values.append(team_values)

答案 3 :(得分:0)

我认为您的循环逻辑只需要很小的改变:

teams_values = []
for team in team_rows:
    team_data = team.find_all("td")
    team_values = []
    for data in team_data:
        if hasattr(data, 'attrs') and 'data-val' in data.attrs:
            #print("\t{}".format(data.attrs['data-val']))
            value = data.attrs['data-val']
            #print(value)
            team_values.append(value)
            #print(team_values)
    teams_values.append(team_values)
print teams_values # should show what you want