如何用 Python 中的列表除以一个整数?
How to divide an integer by a list in Python?
sample = [['AAAA','BBBB','CCCC'],['BBBBB','FFFFF','GGGGG'],['AA','MM']]
我需要计算 'a' 使得 a = 求和 1/i;其中 i 的范围从 1 到 n-1。在此过程中,我需要将一个整数(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
但是,我得到的输出为 [[1.0]],而我应该得到的输出为列表中的 [1.83333333333, 2.08333333333,1] 数字。
知道我可能哪里出错了吗?
假设你在谈论(整数除法)。我更喜欢使用 Numpy。以下可能是您要查找的内容:
import numpy as np
a = np.array([1,2,3,4,5]) # a List
b = 3 # INT Value
print b/a
如果我理解得很好,您想将 a
除以列表中的每个元素。
你需要的是 reduce
:
l = [1, 2, 3, 4]
reduce((lambda x, y : x/y), l)
将 return l
的第一个元素,即 1
除以 l
的所有其他元素。
说明
reduce
将第一个参数应用到第二个参数的前两个元素,并用一个新的列表重复它,这个列表的第一个元素是调用的结果,其他元素是调用的元素passed list,从第3个开始,直到第二个参数只有一个元素。
示例调用说明:
>>>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
表示 "you know, that function that takes two arguments and that returns their quotient"。这是一个匿名函数。
I need to calculate 'a' such that a = summation 1/i; where i ranges from 1 to 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
这是你想要做的吗?
sample = [['AAAA','BBBB','CCCC'],['BBBBB','FFFFF','GGGGG'],['AA','MM']]
我需要计算 'a' 使得 a = 求和 1/i;其中 i 的范围从 1 到 n-1。在此过程中,我需要将一个整数(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
但是,我得到的输出为 [[1.0]],而我应该得到的输出为列表中的 [1.83333333333, 2.08333333333,1] 数字。
知道我可能哪里出错了吗?
假设你在谈论(整数除法)。我更喜欢使用 Numpy。以下可能是您要查找的内容:
import numpy as np
a = np.array([1,2,3,4,5]) # a List
b = 3 # INT Value
print b/a
如果我理解得很好,您想将 a
除以列表中的每个元素。
你需要的是 reduce
:
l = [1, 2, 3, 4]
reduce((lambda x, y : x/y), l)
将 return l
的第一个元素,即 1
除以 l
的所有其他元素。
说明
reduce
将第一个参数应用到第二个参数的前两个元素,并用一个新的列表重复它,这个列表的第一个元素是调用的结果,其他元素是调用的元素passed list,从第3个开始,直到第二个参数只有一个元素。
示例调用说明:
>>>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
表示 "you know, that function that takes two arguments and that returns their quotient"。这是一个匿名函数。
I need to calculate 'a' such that a = summation 1/i; where i ranges from 1 to 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
这是你想要做的吗?