简体   繁体   English

Python将csv文件中的某些值读入列表

[英]Python reading certain values from a csv file into a list

I am having some trouble reading specific data from a csv file into a list in Python. 我在将csv文件中的特定数据读入Python列表时遇到一些麻烦。 Below is an example of my csv file: 以下是我的csv文件的示例:

Round 1
Player1  Score  Player2  Score
P1       5      P2       3
P3       2      P4       4
Round 2
Player1  Score  Player2  Score
P1       3      P4       6
Round 3...

(The cells are merged across the top for Round 1 and Round 2) (第1轮和第2轮的单元格合并在顶部)

I am able to append all of the data in this csv file into a list however, I am wanting to ignore the row that contain "Round 1" and the row below it that contains "Player1", "Score" etc and just append the data. 我可以将此csv文件中的所有数据追加到列表中,但是,我想忽略包含“ Round 1”的行以及其下方包含“ Player1”,“ Score”等的行,而仅追加数据。 The same goes for the "Round 2" row and the row below. “ Round 2”行和下面的行也是如此。 The desired list will look something like: [[P1, 5, P2, 3][P3, 2, P4, 4][P1, 3, P4, 6]]. 所需的列表将类似于:[[P1、5,P2、3] [P3、2,P4、4] [P1、3,P4、6]]。 Below is an example of my code: 以下是我的代码示例:

playerScores = []
with open(scoreFile) as scores
    for row in csv.reader(scores)
        playerScores.append(row)

Any help with this would be greatly appreciated as I am struggling (PS I tried to use "next(scoreFile)" however, it only got rid of the header "Round 1" for me) 在此过程中遇到的任何帮助将不胜感激(PS我尝试使用“ next(scoreFile)”,但对我来说,它仅摆脱了标题“ Round 1”)

Cheers, 干杯,

What about simple if condition? if条件简单怎么办?

playerScores = []
with open(scoreFile) as scores
    for row in csv.reader(scores):
        if row and not row[0].startswith('Round') and not row[0].startswith('Player'):
            playerScores.append(row)

To start from Round 2 从第二轮开始

either you can add a new flag later_rounds : 您也可以添加一个新的标记later_rounds

playerScores = []
later_rounds = False
with open(scoreFile) as scores:
    for row in csv.reader(scores):
        if row and row[0].startswith('Round 2'):
            later_rounds = True 
        if later_rounds and row and not row[0].startswith('Round') and not row[0].startswith('Player'):
            playerScores.append(row)

Or you can skip the beginning in another loop: 或者,您可以跳过另一个循环的开头:

playerScores = []
with open(scoreFile) as scores:
    scoreReader = csv.reader(scores)
    for row in scoreReader:
        if row and row[0].startswith('Round 2'):
            break
    for row in scoreReader:
        if row and not row[0].startswith('Round') and not row[0].startswith('Player'):
            playerScores.append(row) 

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

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