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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从python中的CSV文件中的列中选择一个随机值?相关的知识,希望对你有一定的参考价值。

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

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

答案

您可以使用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?']

以上是关于如何从python中的CSV文件中的列中选择一个随机值?的主要内容,如果未能解决你的问题,请参考以下文章

当我将 pandas 数据框保存为 csv 文件时,从 18 位长的列中截断 3 位

如何从.csv文件向JTable中的列添加标头

去掉 从R中的列中的值[重复]

从巨大的 CSV 文件中读取随机行

从csv文件(python)的列中查找最大2(或n)个值[重复]

如何将数据从 python 列表中的列和行写入 csv 文件?