列表未改组 python
list not shuffling python
我这里的代码应该随机播放包含 "ace of hearts" "two of hearts" 和 "three of hearts" 的列表。
它可以很好地从文件中检索它们,但不会打乱它们的顺序,只是将列表打印两次。据我所知,列表可以包含单词 - 但我似乎弄错了。
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
split
函数returns一个列表,所以不需要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
也不需要使用 with open(...)
语法的 f.close()
。
我认为问题是当您实际上只想获取文件的第一行时,您循环了文件 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
我这里的代码应该随机播放包含 "ace of hearts" "two of hearts" 和 "three of hearts" 的列表。
它可以很好地从文件中检索它们,但不会打乱它们的顺序,只是将列表打印两次。据我所知,列表可以包含单词 - 但我似乎弄错了。
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
split
函数returns一个列表,所以不需要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
也不需要使用 with open(...)
语法的 f.close()
。
我认为问题是当您实际上只想获取文件的第一行时,您循环了文件 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