简体   繁体   中英

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)?

In your second attempt, you're printing the line variable directly. You should print the items from the results list. Something like this should work:

results = []

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

You might want to take the internal for loop I added out depending on how you want your results to show.

The first works -- except you shuffle the list again and again, after adding each line. Once at the end is enough.

The second does the same, except you don't print the list, you print the line you just added. Those are in the order in which they are in the file.

The third fails because you can't shuffle a string (because it's immutable). It makes no sense anyway.

The '\\n' characters are newlines from the file. Use the string method .strip() to remove them.

Files have a handy helper method readlines() to read all the lines into a list at once.

But if you also want to use strip , it's easier to use a list comprehension:

with open('countries.txt') as inputfile:
    results = [line.strip() for line in inputfile]
results.shuffle()
for result in results:
    print(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM