如何创建一个提示输入项目列表的循环,每次都会改变提示。
例如"输入你的第一个项目"然后"输入你的第二项"等...(或第1,第2)
我需要将所有项添加到数组中:
items = []
for i in range(5):
item = input("Input your first thing: ")
items.append(item)
print (items)
答案 0 :(得分:6)
使用提示列表:
prompts = ('first', 'second', 'third', 'fourth', 'fifth')
items = []
for prompt in prompts:
item = input("Input your {} thing: ".format(prompt))
items.append(item)
答案 1 :(得分:4)
略微改变你的代码:
names = {1: "first", 2: "second", 3: "third" # and so on...
}
items = []
for i in range(5):
item = input("Input your {} thing: ".format(names[i+1])
items.append(item)
print(items)
或更通用的版本:
def getordinal(n): 如果str(n)[ - 2:] in(“11”,“12”,“13”): 返回“{} th”.format(n) elif str(n)[ - 1] ==“1”: return“{} st”.format(n) elif str(n)[ - 1] ==“2”: return“{} nd”.format(n) elif str(n)[ - 1] ==“3”: return“{} rd”.format(n) 其他: 返回“{} th”.format(n)
或更紧凑的定义:
def getord(n):
s=str(n)
return s+("th" if s[-2:] in ("11","12","13") else ((["st","nd","rd"]+
["th" for i in range(7)])
[int(s[-1])-1]))
答案 2 :(得分:2)
为什么不使用字符串格式?
的内容>>> for i in range(5):
items.append(input("Enter item at position {}: ".format(i)))
答案 3 :(得分:0)
from collections import OrderedDict
items = OrderedDict.fromkeys(['first', 'second', 'third', 'fourth', 'fifth'])
for item in items:
items[item] = raw_input("Input your {} item: ".format(item))
print items
输出:
Input your first item: foo
Input your second item: bar
Input your third item: baz
Input your fourth item: python
Input your fifth item: rocks
OrderedDict([('first', 'foo'), ('second', 'bar'), ('third', 'baz'), ('fourth', 'python'), ('fifth', 'rocks')])