如何创建一个提示输入项目列表的循环,每次提示都会更改。
例如“输入你的第一个项目”然后“输入你的第二个项目”等等......(或第一个,第二个)
我需要将所有项目添加到数组中:
items = []
for i in range(5):
item = input("Input your first thing: ")
items.append(item)
print (items)
使用提示列表:
prompts = ('first', 'second', 'third', 'fourth', 'fifth')
items = []
for prompt in prompts:
item = input("Input your {} thing: ".format(prompt))
items.append(item)
稍微改变你的代码:
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): if str(n)[-2:] in ("11","12","13"): return "{}th".format(n) elif str(n)[-1 ] == "1": 返回 "{}st".format(n) elif str(n)[-1] == "2": 返回 "{}nd".format(n) elif str(n)[ -1] == "3":返回 "{}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]))
为什么不使用字符串格式?类似的东西
>>> for i in range(5):
items.append(input("Enter item at position {}: ".format(i)))
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')])