我有九个变量和一个函数,但是我关注这个问题的变量部分。 (此代码的前九行。)
groceryfruits1 = 'The number of fruit(s) in the grocery bag is: 1.'
groceryfruits2 = 'The number of fruit(s) in the grocery bag is: 2.'
groceryfruits3 = 'The number of fruit(s) in the grocery bag is: 3.'
groceryfruits4 = 'The number of fruit(s) in the grocery bag is: 4.'
groceryfruits5 = 'The number of fruit(s) in the grocery bag is: 5.'
groceryfruits6 = 'The number of fruit(s) in the grocery bag is: 6.'
groceryfruits7 = 'The number of fruit(s) in the grocery bag is: 7.'
groceryfruits8 = 'The number of fruit(s) in the grocery bag is: 8.'
groceryfruits9 = 'The number of fruit(s) in the grocery bag is: 9.'
def checkout(itemcount, category):
if category == "fruits":
if itemcount == 1:
print groceryfruits1
elif itemcount == 2:
print groceryfruits2
elif itemcount == 3:
print groceryfruits3
elif itemcount == 4:
print groceryfruits4
elif itemcount == 5:
print groceryfruits5
elif itemcount == 6:
print groceryfruits6
elif itemcount == 7:
print groceryfruits7
elif itemcount == 8:
print groceryfruits8
elif itemcount == 9:
print groceryfruits9
checkout(9, "fruits")
由于存在一个连续的变量列表,并且将所有变量放在一行中会更加有序,有没有办法做到这一点?
答案 0 :(得分:3)
您可以将代码简化为:
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")
答案 1 :(得分:3)
水果计数之前的字符串总是相同的,那么为什么不将它编码到你的函数中?
def checkout(itemcount, category):
if category == 'fruits':
print 'The number of fruit(s) in the grocery bag is: {0}.'.format(itemcount)
一旦你有更多的项目类别,你可能会考虑像这样(或类似的)编写你的函数,以允许更多的灵活性:
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)
演示:
>>> 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
答案 2 :(得分:0)
通常,一组类似命名的变量应合并为一个列表。 (为此,我们忽略了值本身是相似的,其他答案都是优越的。)
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")