我在这里拥有的代码应该对包含“红心王牌”,“两红心”和“三红心”的列表进行改组。
它可以很好地从文件中检索它们,但不会洗牌,只需将列表打印两次即可。据我所知,列表中可以包含单词-但是似乎我弄错了。
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
我认为问题在于,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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句