我需要操作list来获得减法(从右边的每个数字中减去每个数字)。
我试过使用下面的代码,它与2个for循环一起工作,不管怎样,我可以只用1个for循环,或者以一种比我做的更好的方式。
list=[3,2,5,4,3]
output_list = [0]
for element in list:
for i in range(0, length(list)):
new_element = [ (list[i] - element) if i > index(element) else 0]
if new_element > 0:
output_list.append( new_element )
示例:输入[3,2,5,4,3]
像[2-3, 5-3, 4-3, 3-3, 5-2, 4-2, 3-2, 4-5, 3-5, 3-4] = [-1, 2, 1, 0, 3, 2, 1, -1, -2, 1]
一样减去
值> 0的输出,第一个0来自initialization [0, 2, 1, 3, 2, 1, 1]
发布于 2019-05-29 23:29:35
这应该会生成正确的输出:
values = [3,2,5,4,3]
print([j-i for k,i in enumerate(values[:-1]) for j in values[k+1:] if j-i > 0])
发布于 2019-05-29 23:30:13
试试这个,你可以使用itertools.combinations
>>> from itertools import combinations
>>> from operator import sub
>>> l = [3,2,5,4,3]
>>> [0]+[sub(c[1],c[0]) for c in combinations(l,2) if sub(c[1],c[0]) > 0]
[0, 2, 1, 3, 2, 1]
发布于 2019-05-30 00:27:54
使用列表理解
a=[3,2,5,4,3]
b= [j-a[i] for i,v in enumerate(a) for j in a[i+1:] if j-a[i]>0]
print(b)
输出
[2, 1, 3, 2, 1]
https://stackoverflow.com/questions/56363839
复制相似问题