【问题标题】:Python choice in an ordered array, picking value one after another有序数组中的Python选择,一个接一个地选择值
【发布时间】:2020-03-25 11:55:50
【问题描述】:

我正在尝试在 python 上做一个简单的过程,我知道这里有一个关于如何实现这一点的答案,但我似乎找不到它。

Python 应该从 txt 文件中的数据列表中进行选择,但要以有序的形式。假设它会在提示时选择第一个值,然后是第二个值,依此类推,直到列表用完。

有没有办法在没有随机的情况下实现这一点?到目前为止我看到的唯一方法是随机的,随机的,没有/有替换。选择的顺序在这里非常重要。

              import random
              with open ("questions.txt","r") as f:
              question = f.readlines()
              post = (random.choice(question).strip())
              print (post)

上面的代码只是随机执行而不是我想要的,我希望它排序并在列表完成时停止。

【问题讨论】:

    标签: python python-3.x random choice


    【解决方案1】:
    with open ("questions.txt","r") as f:
        question = f.readlines()
    for each in question:
        print(each.strip())
    

    或者如果您想拥有更多控制权,您可以在 Iterator 上使用next(并处理迭代结束异常):

    with open ("questions.txt","r") as f:
        questions = iter(f.readlines())
    
    while True:
        try:
            question = next(questions)
        except StopIteration:
            # no more questions
        else:
            # handle `question`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多