Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
列表不洗牌python_Python_Python 3.x_List_Random_Shuffle - Fatal编程技术网

列表不洗牌python

列表不洗牌python,python,python-3.x,list,random,shuffle,Python,Python 3.x,List,Random,Shuffle,我这里的代码应该将包含“红桃王牌”、“红桃二号”和“红桃三号”的列表洗牌 它可以很好地从文件中检索它们,但不会洗牌它们,只需将列表打印两次。据我所知,一份清单可以包括单词——但似乎我错了 import random def cards_random_shuffle(): with open('cards.txt') as f: cards = [words.strip().split(":") for words in f] f.close() r

我这里的代码应该将包含“红桃王牌”、“红桃二号”和“红桃三号”的列表洗牌

它可以很好地从文件中检索它们,但不会洗牌它们,只需将列表打印两次。据我所知,一份清单可以包括单词——但似乎我错了

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
函数返回一个列表,因此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

也不需要使用带有open(…)
语法的
来使用
f.close()

我假设问题是,当您实际上只想获取文件的第一行时,您在文件
中的行上循环查找f
中的单词

假设您的文件如下所示:

红桃王牌:红桃二人:红桃三人

那么您只需要使用第一行:

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

@打印(卡片)的输出是什么样子的?@MatthewFitch[['Ace of Hearts','Two of Hearts','Three of Hearts']]@ggfdsdc啊,你有一个嵌套列表。您需要执行random.shuffle(卡片[0])或类似于洗单词列表的操作。或者对“cards=[words.strip()…”行进行更改,因为方括号使其成为嵌套列表。@MatthewFitch谢谢。它本身也会打印两次。有什么想法吗?cards.txt是什么样子的吗?还有一个问题-我如何选择列表中的单个项目-我已经尝试过cards[1,3,4]正如我被告知要做的,但它似乎不起作用,“必须是整数而不是元组”,而且这个主题的答案都不清楚me@ggfdsdc使用
卡[0]
(第一张卡)可以访问单个项目。您不能按索引(仅按片,例如
卡[0:2]
第一张和第二张卡)拾取多张卡使用普通列表。。