【问题标题】:Python 3 How to return separate list from deriving quotient and remainderPython 3 如何从导出商和余数返回单独的列表
【发布时间】:2020-07-20 10:06:07
【问题描述】:

我需要帮助来创建两个列表;一个商,一个余数。

例如。 y = [20, 7, 88, 66, 18] 和 d = 9

在将数字从列表 (y) 中除之后,我想生成一个单独的列表来分别托管商和余数;而不是逐步添加更多列表。基本上,我希望输出代码生成如下:

这是商。

[2, 0, 9, 7, 2]

这是余数。

[2, 7, 7, 3, 0]

目前,我的代码使其生成如下:

//(输入)//

#def calculate_quotient_and_remainder(y, d):

y = [20, 7, 88, 66, 18]
d = 9
r = []
q = []
print('This is the quotient.')

#def returnQuotient():

for i, one_a in enumerate(y):
    r.append(one_a // d) 
    print (r)
    
print('\n') 

#def returnRemainder():
print('This is the remainder.')
for j, one_b in enumerate(y): 
    q.append(one_b % d)
    print (q)

//(输出)//

这是商。

[2]

[2, 0]

[2, 0, 9]

[2, 0, 9, 7]

[2, 0, 9, 7, 2]

这是余数。

[2]

[2, 7]

[2, 7, 7]

[2, 7, 7, 3]

[2, 7, 7, 3, 0]

请帮忙!

【问题讨论】:

  • 请格式化您的代码
  • 在循环结束后只使用一次print

标签: python python-3.x list function


【解决方案1】:

在每个循环之后只使用一次print 可以解决您的问题。另外,首先,您可以定义一个函数:

def calculate_quotient_and_remainder(y, d):
    quotients = [] 
    remainders = [] 
    for num in y:
        quotients.append(num // d) # This is interger division. Use "int(num/d)" if you want.
        remainders.append(num % d)
        
    return quotients, remainders

然后,您可以调用并打印商和余数:

y = [20, 7, 88, 66, 18]
d = 9
q, r = calculate_quotient_and_remainder(y, d)
print('Quotients:', q)
print('Remainders:', r)

输出:

Quotients: [2, 0, 9, 7, 2]
Remainders: [2, 7, 7, 3, 0]

【讨论】:

    【解决方案2】:

    使用列表推导:

    y = [20, 7, 88, 66, 18] 
    d = 9
    
    quotient = [i//d for i in y]
    reminder = [i%d for i in y]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多