如何根据索引值生成列表

时间:2014-02-26 00:24:02

标签: python

我正在尝试根据用户提示生成一个由0组成的列表。如果他们输入一个,那么一个索引将被替换为一个,如果他们输入两个,则两个索引将被替换为一个,等等。我能够生成一个和零的随机列表但是我遇到了麻烦输入。
这是我到目前为止所做的:

import random

def askTheUser():
  number = input("Do you want to roll again? Pick a number or numbers thru 0 and 5:")
  myList = []
  aList = [1,0]
  for i in range(5):
    myList.append(random.choice(aList))
    if number == 1:
        return myList[1] = 0
    if number == 2:
        return myList[2] = 0

return myList




print(askTheUser())

2 个答案:

答案 0 :(得分:1)

我认为你用0替换不是1,输入也是取字符串而不是int所以尝试转换它 和list index是基于0的,所以正确的代码应该是:

import random

def askTheUser():
  number = input("Do you want to roll again? Pick a number or numbers thru 0 and 4:")
  myList = []
  aList = [1,0]
  for i in range(5):
    myList.append(random.choice(aList))
  myList[int(number)] = 1

  return myList
print(askTheUser())

答案 1 :(得分:1)

我不确定你的程序应该做什么。我试图比你的代码更多地遵循描述(欢迎预期的输入和输出)。 这是我的作品:

from __future__ import print_function # make it work also in python 2.x
import random

def askTheUser():
    # don't use magic numbers, use 'constant-like' variables
    MAX = 5

    # try to avoid too long lines if possible
    msg = "Do you want to roll again? " +\
        "Pick a number or numbers thru 0 and {}: ".format(MAX)

    # you should use raw_input() for asking user, input() is very unsafe
    number = raw_input(msg)

    # initialize with random [0,1]
    myList = [random.randint(0,1) for i in range(MAX)]

    try:
        # you need to convert string to int
        i = int(number, 10)

        # negative indexes can be valid ;o)
        # let's not allow for that in this case, throwing error
        if i < 0:
            raise IndexError
        myList[i] = 1

    # you may expect ValueError if string was not valid integer
    # or IndexError if it was beyond range (0, MAX)
    except (IndexError, ValueError):
        print ("That was wrong value:", number) # if you want, message user
        pass
    finally:
        return myList

if __name__ == '__main__':
    print(askTheUser())

如果要一次接受多个值,则应在输入上使用split()并在循环中处理它们。 祝你好运。