python - 列表不改组 python

标签 python python-3.x list random shuffle

我这里的代码应该洗牌包含“红心 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/

相关文章:

python - 从 Excel 多表文件 : List comprehension between columns 解析

python - 在一个框中输入一个值会更新所有框吗?

c - 扩展模块: marshalling void * to bytearray (and/or vice versa)

python - 如何在Python中改善列表上的模式匹配

javascript - 使用 Javascript 将列表值发送到文本框

python - 如何用多个分隔符分割字符串并存储在列表中?

python - Durand-kerner 实现不起作用

python - 为 Sublime Text 3 Anaconda 插件设置 PATH

python - 如何使用 Gtk.Builder 创建带有菜单栏的 PyGObject 应用程序?

Python,复制具有不同值的 2 级列表结构