[英]Merging 9 Sequential Variables into 1 Variable
我在下面有9个变量和一个函数,但是我专注于此问题的变量部分。 (此代码的前九行。)
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")
由于存在一个顺序的变量列表,并且将所有变量放在一行中会更加有序,是否有任何方法可以做到这一点?
您可以将代码简化为:
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)
一旦有了更多的项目类别,您可能需要考虑像这样(或类似方式)编写函数,以实现更大的灵活性:
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
通常,应将一组名称相似的变量合并为一个列表。 (为此,我们将忽略值本身是相似的,而其他答案是优越的。)
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.