列表没有改组python

时间:2017-08-22 12:32:19

标签: python python-3.x list random shuffle

我在这里的代码应该改组包含"心灵" "心中的两个"和"心中的三个"。

它可以很好地从文件中检索它们,但它不会对它们进行随机播放,只需将列表打印两次。据我所知,列表可以包含单词 - 但似乎我错了。

import random
def cards_random_shuffle():
    with open('cards.txt') as f:
        cards = [words.strip().split(":") for words in f]
        f.close()
    random.shuffle(cards)
    print(cards)
    return cards

2 个答案:

答案 0 :(得分:0)

split函数返回一个列表,因此不需要for words in f

import random
def cards_random_shuffle():
        with open('cards.txt') as f:
            cards = []
            for line in f:
                cards += line.strip().split(":")
        random.shuffle(cards)
        print(cards)
        return cards

f.close()语法也不需要with open(...)

答案 1 :(得分:0)

我认为问题在于,当您实际上只想获取文件的第一行时,您会遍历文件for words in f中的行。

假设您的文件如下所示:

Ace of Hearts:Two of Hearts:Three of Hearts

然后你只需要使用第一行:

import random
def cards_random_shuffle():
    with open('cards.txt') as f:
        firstline = next(f)
        cards = firstline.strip().split(':')
        # an alternative would be to read in the whole file:
        # cards = f.read().strip().split(':')
    print(cards)    # original order
    random.shuffle(cards)
    print(cards)    # new order
    return cards