Python将csv文件中的某些值读取到lis中

2024-09-28 04:21:36 发布

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

我在用Python将csv文件中的特定数据读入列表时遇到了一些问题。下面是我的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...

(第一轮和第二轮的单元格在顶部合并)

我可以将这个csv文件中的所有数据添加到一个列表中,但是我想忽略包含“第1轮”的行和它下面包含“Player1”、“Score”等的行,只添加数据。“第二轮”行和下面的行也是如此。所需的列表将类似于:[[P1,5,P2,3][P3,2,P4,4][P1,3,P4,6]]。下面是我的代码示例:

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

任何帮助,这将是非常感谢,因为我正在挣扎(PS我试图使用“下一个(记分文件)”,但它只是摆脱了标题“第一轮”为我)

干杯


Tags: 文件csv数据示例列表scorep2p3
2条回答

从第二轮开始

您可以添加一个新标志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)

或者可以跳过另一个循环的开头:

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) 

那么简单的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)

相关问题 更多 >

    热门问题