【问题标题】:list not shuffling python列表不洗牌python
【发布时间】:2018-01-30 17:55:58
【问题描述】:

我这里的代码应该洗牌包含“红心王牌”“红心二”和“红心三”的列表。

它可以很好地从文件中检索它们,但它不会打乱它们并且只是打印列表两次。据我所知,列表可以包含单词 - 但是我似乎弄错了。

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

【问题讨论】:

  • @ggfdsdc print(cards) 的输出是什么样的?
  • @MatthewFitch [['红心王牌','红心二','红心三']]
  • @ggfdsdc 啊,你有一个嵌套列表。你需要做 random.shuffle(cards[0]) 或类似的东西来打乱单词列表。或者更改“cards = [words.strip()...”行,因为方括号使其成为嵌套列表。
  • @MatthewFitch 谢谢。它还会自行打印两次。有什么想法吗?
  • cards.txt 是什么样子的?

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


【解决方案1】:

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(...) 语法。

【讨论】:

    【解决方案2】:

    我认为问题在于,当您实际上只想获取文件的第一行时,您会遍历文件 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
    

    【讨论】:

    • 另一个问题-我将如何选择列表中的单个项目-我已经尝试了卡片 [1,3,4],因为我被告知要这样做,但它似乎不起作用“必须是整数而不是元组”,我对这个主题的答案都不清楚
    • @ggfdsdc 可以使用cards[0](第一张卡)访问单个项目。您不能使用普通列表按索引选择多张卡片(仅按切片,例如cards[0:2] 第一张和第二张卡片)。
    猜你喜欢
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多