【发布时间】: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