简体   繁体   English

从数组Python中的文本文件中随机字符串列表?

[英]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 . 我有一个文本文件,其中列出了几个国家,称为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) . 产生错误的特定行是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)? 那么,如何将列表从文本文件获取到数组中,将列表随机化并打印结果(不带[]"\\n"并且以第二列表中所示的常规列表格式显示)?

In your second attempt, you're printing the line variable directly. 第二次尝试是直接打印line变量。 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. 您可能希望采用我添加的内部for循环,具体取决于您希望结果如何显示。

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. '\\n'字符是文件中的换行符。 Use the string method .strip() to remove them. 使用字符串方法.strip()删除它们。

Files have a handy helper method readlines() to read all the lines into a list at once. 文件具有方便的帮助程序方法readlines() ,可将所有行一次读取到列表中。

But if you also want to use strip , it's easier to use a list comprehension: 但是,如果您还想使用strip ,那么使用列表推导会更容易:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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