因此,我可以使用以下代码轻松打印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?
如何让它随机选择其中一个问题以及选择列?
答案 0 :(得分:1)
您可以使用random.choice
在csv中获取随机行,如:
csv_reader = csv.reader(data)
questions = list(csv_reader)
random_question = random.choice(questions)
请注意,这将返回与csv行对应的列表。要获取特定列,您可以选择:
text = random_question[column_needed]
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?']