简体   繁体   English

问题附加到 python 中的列表

[英]Issues appending to a list in python

I have the following data file.我有以下数据文件。

>| --- | | Adelaide | | --- | |  2021 | | --- | | Rnd | T | Opponent | Scoring | F | Scoring | A | R | M | W-D-L | Venue | Crowd |
> Date | | R1 | H | Geelong | 4.4 11.7 13.9 15.13  | 103 | 2.3 5.5 10.8
> 13.13  | 91 | W | 12 | 1-0-0 | Adelaide Oval |  26985 | Sat 20-Mar-2021 4:05 PM | | R2 | A | Sydney | 3.2 4.6 6.14 11.22  | 88 |
> 4.1 9.6 15.11 18.13  | 121 | L | -33 | 1-0-1 | S.C.G. |  23946 | Sat 27-Mar-2021 1:45 PM |

I created a code to manipulate that data to my desired results which is a list.我创建了一个代码来将该数据操作为我想要的结果,这是一个列表。 When I print my variable row at the current spot it prints correctly.当我在当前位置打印可变行时,它打印正确。 However, when I append my list row to another list my_array I have issues.但是,当我 append 我的列表行到另一个列表 my_array 时,我遇到了问题。 I get an empty list returned.我得到一个空列表返回。 I think the issue is the placement of where I am appending?我认为问题是我要追加的位置? My code is this:我的代码是这样的:

with open('adelaide.md', 'r') as f:
    my_array = []
    team = ''
    year = ''
    for line in f:
        row=[]
        line = line.strip()
        fields = line.split('|')
        num_fields = len(fields)
        if len(fields) == 3:
            val = fields[1].strip()
        if val.isnumeric():
            year = val
        elif val != '---':
            team = val   
        elif num_fields == 15:
            row.append(team)
            row.append(year)
            for i in range(1, 14):
                row.append(fields[i].strip())
            print(row)
    my_array.append(row)      

You need to append the row array inside the for loop.您需要 append for 循环内的行数组。

I think last line should be inside the for loop.我认为最后一行应该在 for 循环内。 Your code is probably appending the last 'row' list.您的代码可能会附加最后一个“行”列表。 Just give it a tab.只需给它一个标签。

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

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