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)

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.

>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

Leave a Reply Cancel reply