我这里的代码应该洗牌包含“红心 A”、“红心二”和“红心三”的列表。
它可以很好地从文件中检索它们,但不会打乱它们的顺序,只是将列表打印两次。据我所知,列表可以包含单词 - 但我似乎错了。
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
中循环遍历行。
假设您的文件如下所示:
红心 A:红心二:红心三
那么你只需要使用第一行:
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
关于python - 列表不改组 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45817755/