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

问题描述 投票:1回答:1

因此,我可以使用以下代码轻松地在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])

反过来又返回:

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?

如何让它随机选择其中一个问题以及选择列?

python csv random
1个回答
1
投票

您可以使用random.choice在csv中获取随机行,如:

Code:

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

请注意,这将返回与csv行对应的列表。要获取特定列,您可以选择:

text = random_question[column_needed]

Test Code:

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)

Results:

['What is 142 in binary?']
© www.soinside.com 2019 - 2024. All rights reserved.