Randomize a string list from a text file in an array Python? -
i have text file several countries listed in called countries.txt
. trying take countries text file , place them in array randomized , randomized list gets printed. have tried editing code in few ways , none of them produce outcome want.
below first way tried it. know i'm printing actual array trying something:
results = [] def load(): open('countries.txt') inputfile: line in inputfile: results.append(line) random.shuffle(results) print(str(results))
and outcome follows:
['armenia\n'] ['bangladesh\n', 'armenia\n'] ['china\n', 'armenia\n', 'bangladesh\n'] ['denmark\n', 'bangladesh\n', 'armenia\n', 'china\n'] ['armenia\n', 'bangladesh\n', 'denmark\n', 'china\n', 'estonia\n'] ['armenia\n', 'estonia\n', 'bangladesh\n', 'china\n', 'france\n', 'denmark\n'] ['france\n', 'china\n', 'bangladesh\n', 'armenia\n', 'estonia\n', 'denmark\n', 'ghana']
the second attempt used following code below:
results = [] def load(): open('countries.txt') inputfile: line in inputfile: results.append(line) random.shuffle(results) print(str(line))
and outcome right in sense listed countries way wanted it, did not randomize them. outcome was:
armenia bangladesh china denmark estonia france ghana
the last attempt made following code:
results = []
def load(): open('countries.txt') inputfile: line in inputfile: results.append(line) random.shuffle(line) print(str(line))
but function produced following error:
file "c:\users\redcode\appdata\local\programs\python\python36-32\lib\random.py", line 274, in shuffle x[i], x[j] = x[j], x[i] typeerror: 'str' object not support item assignment
and specific line producing error random.shuffle(line)
.
am missing or there different way because cannot find different i've been trying.
so how can list text file array, randomize list , print outcome (without []
or "\n"
, in normal list format shown in second example)?
the first works -- except shuffle list again , again, after adding each line. once @ end enough.
the second same, except don't print list, print line added. in order in in file.
the third fails because can't shuffle string (because it's immutable). makes no sense anyway.
the '\n'
characters newlines file. use string method .strip()
remove them.
files have handy helper method readlines()
read lines list @ once.
but if want use strip
, it's easier use list comprehension:
with open('countries.txt') inputfile: results = [line.strip() line in inputfile] results.shuffle() result in results: print(result)
Comments
Post a Comment