简体   繁体   English

如何在Python中将整数除以列表?

[英]How to divide an integer by a list in Python?

sample = [['AAAA','BBBB','CCCC'],['BBBBB','FFFFF','GGGGG'],['AA','MM']]

I need to calculate 'a' such that a = summation 1/i; 我需要计算“ a”,使a =总和1 / i; where i ranges from 1 to n-1. 我的范围是1到n-1。 In the process, I need to divide an integer (MyInt) by a list. 在此过程中,我需要将整数(MyInt)除以列表。

i2 =[]
afinal =[]
for sub_list in sample:
    i1 = range(len(sample[0]))
    i1.pop(0)
    myInt = [1 for x in i1]
    newList = [float(int1)/float(x) for int1,x in zip(myInt,i1)]
    a = [sum(i) for i in zip(newList)]
afinal.append(a)
print afinal

However, I get the output as [[1.0]], whereas I should be getting an output with as [1.83333333333, 2.08333333333,1] numbers within a list. 但是,我得到的输出为[[1.0]],而我应该在列表中得到的输出为[1.83333333333,2.08333333333,1]。

Any idea where I may be going wrong? 知道我可能会出错吗?

I need to calculate 'a' such that a = summation 1/i; 我需要计算“ a”,使a =总和1 / i; where i ranges from 1 to n-1 我的范围是1到n-1

>>> n = 5
>>> a = sum(1.0 / i for i in range(1,n))
>>> a
2.083333333333333
>>> 1./1 + 1./2 + 1./3 + 1./4
2.083333333333333

Is that what you are trying to do? 那是你想做的吗?

If I understand well, you want to divide a by every element of your list. 据我了解,您想将a除以列表中的每个元素。 What you need is reduce : 您需要的是reduce

l = [1, 2, 3, 4]
reduce((lambda x, y : x/y), l)

Will return the first element of l , which is 1 , divided by all the other elements of l . 将返回l的第一个元素(即1 )除以l所有其他元素。

Explanation 说明

reduce applies the first parameter to the first two elements of the second parameter, and repeats it with a new list whose first element is the result of the call, and the other elements are the elements of the passed list, started from the 3rd, until the second parameter has only one element. reduce将第一个参数应用于第二个参数的前两个元素,并用一个新列表重复它,第一个元素是调用的结果,其他元素是传递的列表的元素,从第3个开始,直到第二个参数只有一个元素。

Example call to clarify: 示例调用以澄清:

>>>reduce((lambda x, y : x+y), [1, 2, 3])
step 1: 1+2=3, so the new call is reduce((lambda x, y : x+y), [3, 3])
step 2: 3+3=6, so the new call is reduce((lambda x, y : x+y), [6])
step 3: [6] has only one element, so returns 6.

lambda x, y : x/y means "you know, that function that takes two arguments and that returns their quotient". lambda x, y : x/y表示“您知道,该函数接受两个参数并返回它们的商”。 This is an anonymous function. 这是一个匿名函数。

Assuming you are talking about (Integer division). 假设您正在谈论(整数除法)。 I would prefer using Numpy. 我更喜欢使用Numpy。 Following might be what you are looking for: 以下可能是您正在寻找的:

import numpy as np

a = np.array([1,2,3,4,5])     # a List
b = 3                         # INT Value
print b/a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM