如何在python中从CSV文件的列中选择一个随机值?

2024-05-03 09:05:13 发布

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

因此,我可以使用以下代码轻松打印出CSV中的完整列:

with open("compsci_questions.csv","r") as f:
        if difficulty=="easy":
            csv_reader=csv.reader(f)
            for line in csv_reader:
                print(line[0])

反过来又返回:

^{pr2}$

我如何让它随机选择其中一个问题,以及选择专栏?在


Tags: csv代码inforifaswitheasy
1条回答
网友
1楼 · 发布于 2024-05-03 09:05:13

您可以使用^{}在csv中获得一个随机行,如下所示:

代码:

csv_reader = csv.reader(data)
questions = list(csv_reader)
random_question = random.choice(questions)

注意,这将返回一个与csv行相对应的列表。若要获取特定列,然后可以选择如下所示:

^{pr2}$

测试代码:

data = StringIO(u"""What is the fastest type of storage?
Which register stores the results of calculations carried out by the ALU?
Which bus sends data to the CPU from the RAM?
What is 10110110 in denary?
What is 7D in denary?
In which topology is each computer connected individually to a central point?
What is half a byte known as?
What is 142 in binary?
What is each column known as in a record?
What is a variable which is available anywhere in a program known as?""")

import random
import csv
csv_reader = csv.reader(data)
questions = list(csv_reader)
random_question = random.choice(questions)
print(random_question)

结果:

['What is 142 in binary?']

相关问题 更多 >