python - 如何根据索引值生成列表

标签 python

我正在尝试根据用户提示生成一个由 0 组成的列表。如果他们输入 1,则 1 索引将被 1 替换,如果他们输入 2,则 2 索引将被 1 替换,等等。我能够生成 1 和 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())

最佳答案

我认为您正在替换为 0 而不是 1,输入也采用字符串而不是 int,所以尝试对其进行强制转换 并且列表索引是从 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())

关于python - 如何根据索引值生成列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22029165/

相关文章:

python - 使用 PyYaml 加载特殊字符

python - 使用 Flask 和 CherryPy 提供静态文件

Python:用于使用多边形裁剪光栅图像的函数的代码审查

python - 从字符串中,如何只返回不以元音开头的单词?

python - 为什么 Matplotlib+Basemap 不显示岛屿?

python - 为什么你可以将列表切片超过总索引计数,但不能直接检索所述索引?

python - urlopen windows ftp 错误

模块之间的python全局变量

python - 使 Dash html Table 组件中的表格可排序

python - 为什么 Haystack AutoQuery 被调用两次?