mardi 25 juillet 2017

Randomize a string list from a text file in an array Python?

I have a text file with several countries listed in it called countries.txt. I am trying to take those countries from the text file and place them in an array where they will then be randomized and the randomized list gets printed. I have tried editing the code in a few ways and none of them produce the outcome that I want.

Below is the first way I tried it. I know I'm printing the actual array but I was trying something:

results = []

def load():
    with open('countries.txt') as inputfile:
        for line in inputfile:
            results.append(line)
            random.shuffle(results)
            print(str(results))

And the outcome was as 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 the following code below:

results = []

def load():
    with open('countries.txt') as inputfile:
        for line in inputfile:
            results.append(line)
            random.shuffle(results)
            print(str(line))

And the outcome was right in the sense that it listed the countries the way i wanted it, but it did not randomize them. The outcome was:

Armenia
Bangladesh
China
Denmark
Estonia
France
Ghana

The last attempt I made was with the following code:

results = []

def load():
    with open('countries.txt') as inputfile:
        for line in inputfile:
            results.append(line)
            random.shuffle(line)
            print(str(line))

But this function produced the 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 does not support item assignment

And the specific line producing the error is random.shuffle(line).

Am I missing something or is there a different way to do this because I cannot find anything different from what I've been trying.

So how can I get the list from a text file into an array, randomize that list and print the outcome (without []or "\n" and in a normal list format as shown in the second example)?




Aucun commentaire:

Enregistrer un commentaire