Python 将9个顺序变量合并为1个变量
我在下面有九个变量和一个函数,但是我将重点放在这个问题的变量部分。(此代码的前九行。)Python 将9个顺序变量合并为1个变量,python,Python,我在下面有九个变量和一个函数,但是我将重点放在这个问题的变量部分。(此代码的前九行。) 因为有一个连续的变量列表,而且将所有变量放在一行会更有序,有没有办法做到这一点?您可以将代码简化为: groceryfruits = 'The number of fruit(s) in the grocery bag is: {}.' def checkout(itemcount, category): if category == "fruits": print groceryf
因为有一个连续的变量列表,而且将所有变量放在一行会更有序,有没有办法做到这一点?您可以将代码简化为:
groceryfruits = 'The number of fruit(s) in the grocery bag is: {}.'
def checkout(itemcount, category):
if category == "fruits":
print groceryfruits.format(itemcount)
checkout(9, "fruits")
水果计数前的字符串总是相同的,那么为什么不将其编码到函数中呢
def checkout(itemcount, category):
if category == 'fruits':
print 'The number of fruit(s) in the grocery bag is: {0}.'.format(itemcount)
<> P>一旦你有了更多的项目类别,你可能想考虑编写你的函数(或类似的)来允许更多的灵活性:
def item_checkout(itemcount, category):
print 'the number of {0} items in the grocery bag is: {1}'.format(category, itemcount)
或者,如果您想要一个通用的签出函数,让它接受(itemcount,category)
元组列表:
def total_checkout(items):
'items: list of (itemcount, category) tuples'
for itemcount, category in items:
print 'the number of {0} items in the grocery bag is: {1}'.format(category, itemcount)
演示:
通常,一组类似命名的变量应该组合到一个列表中。(对于这一点,我们将忽略这些值本身是相似的,而其他答案则更优。)
groceryfruits=[
“食品袋中的水果数量为:1。”,
“食品袋中的水果数量为:2。”,
“食品袋中的水果数量为:3。”,
“食品袋中的水果数量为:4。”,
“食品袋中的水果数量为:5。”,
“食品袋中的水果数量为:6。”,
“食品袋中的水果数量为:7。”,
“食品袋中的水果数量为:8。”,
“食品袋中的水果数量为:9。”
]
def签出(itemcount,类别):
如果类别==“水果”:
如果你发现自己在任何时候创建这样的编号变量,你应该考虑使用数组(在Python中称为列表)。
def total_checkout(items):
'items: list of (itemcount, category) tuples'
for itemcount, category in items:
print 'the number of {0} items in the grocery bag is: {1}'.format(category, itemcount)
>>> total_checkout([(5, 'banana'), (2, 'fruit'), (7, 'sirup')])
the number of banana items in the grocery bag is: 5
the number of fruit items in the grocery bag is: 2
the number of sirup items in the grocery bag is: 7
groceryfruits = [
'The number of fruit(s) in the grocery bag is: 1.',
'The number of fruit(s) in the grocery bag is: 2.',
'The number of fruit(s) in the grocery bag is: 3.',
'The number of fruit(s) in the grocery bag is: 4.',
'The number of fruit(s) in the grocery bag is: 5.',
'The number of fruit(s) in the grocery bag is: 6.',
'The number of fruit(s) in the grocery bag is: 7.',
'The number of fruit(s) in the grocery bag is: 8.',
'The number of fruit(s) in the grocery bag is: 9.'
]
def checkout(itemcount, category):
if category == "fruits":
if 1 <= itemcount <= 9:
# List indices start at 0
print groceryfruits[i-1]
checkout(9, "fruits")