Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i set a variable full of numbers into a list?

I have a csv file and managed to get access to it and just get the 6th element of each row into a var (buys).
Now, I want to take these numbers in buys into a new list to take afterwards a random number of the list but I’m struggling creating a list. Can you help me please?

My code is now:

import csv
import random

data = open('data.csv')
dataList = list(csv.reader(data, delimiter=','))

for item in dataList:
    buys = item[6]
    buyslist = list(buys)
    randomNumber = random.choice(buyslist)
    print(buyslist)

and when I print buyslist I get each number into an element like 803 transfered into the list [8][0][3]. But i need [803] :D.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

It sounds like your goal is to select a random row and extract the value found at index 6 in that row. Right now, you’re trying to select a random digit from index 6 in every row.

What you want requires no explicit loop at all:

import csv
import random

with open('data.csv') as data:  # Use with statement for deterministic cleanup
    dataList = list(csv.reader(data, delimiter=','))

randomNumber = random.choice(dataList)[6]  # Select random row, extract relevant column

If you need the whole list of just that row, you can convert once up front, then perform the selection, replacing randomNumber = random.choice(dataList)[6] with:

buyslist = [item[6] for item in dataList]  # Simple listcomp to extract relevant column
                                           # from each row in new list
# Optionally, convert to integer upfront with:
buyslist = [int(item[6]) for item in dataList]  # listcomp to both extracts *and* parses

randomNumber = random.choice(buyslist)  # Select random value from extracted values
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading