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

Time:01-19

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.

enter image description here

CodePudding user response:

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

CodePudding user response:

you can use the .join() method of strings to append your values

   ...
   "".join(buyslist)  # int() for number

NOTE that .join() is a method of the string "", so you can use it to inject separators too (such as ",")

CodePudding user response:

Thank you very much ShadowRanger! You helped me a lot!

My Code:

import csv
import random

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

buys = [item[6] for item in dataList]
randomNumber = random.choice(buys)
print(randomNumber)
  • Related