找到列表元素的所有可能差异
find all the possible differences of the elements of a list
我正在尝试找出一个列表的元素之间所有可能的差异。
例如:
x=[1,4,10,17,20,35].
我想要一个数组作为答案:
y=[3, 9, 16, 19, 34, 3, 6, 13, 16, 31, 9, 6, 7, 10, 25, 16, 13, 10, 3, 18, 19, 16, 10, 3, 15, 34, 31, 25, 18, 15]
对应
[1-4, 1-10, 1-17, 1-20, 1-35, 4-1, 4-10, 4-17, ....]
我已经尝试用 diff 来做到这一点,但我只能得到两个连续数字的差值。而且我真的不知道如何循环计算它。
你能帮忙吗?
写在Java,就这么简单:
List<Integer> diff = new ArrayList<Integer>();
for(int i=0; i<list.size(); i++) {
for(int j=0; j<list.size(); j++) {
if(i != j)
diff.add(Math.abs(list.get(i) - list.get(j)));
}
}
写在python
中的解决方案
elements = [1,4,10,17,20,35]
differences = []
for i , element in enumerate(elements):
for j, element2 in enumerate(elements):
if i != j:
differences.append( abs(element - element2) )
A Python 1 行:
>>> [abs(a - b) for i,a in enumerate(x) for j,b in enumerate(x) if i != j]
[3, 9, 16, 19, 34, 3, 6, 13, 16, 31, 9, 6, 7, 10, 25, 16, 13, 7, 3, 18, 19, 16, 10, 3, 15, 34, 31, 25, 18, 15]
我正在尝试找出一个列表的元素之间所有可能的差异。
例如:
x=[1,4,10,17,20,35].
我想要一个数组作为答案:
y=[3, 9, 16, 19, 34, 3, 6, 13, 16, 31, 9, 6, 7, 10, 25, 16, 13, 10, 3, 18, 19, 16, 10, 3, 15, 34, 31, 25, 18, 15]
对应
[1-4, 1-10, 1-17, 1-20, 1-35, 4-1, 4-10, 4-17, ....]
我已经尝试用 diff 来做到这一点,但我只能得到两个连续数字的差值。而且我真的不知道如何循环计算它。
你能帮忙吗?
写在Java,就这么简单:
List<Integer> diff = new ArrayList<Integer>();
for(int i=0; i<list.size(); i++) {
for(int j=0; j<list.size(); j++) {
if(i != j)
diff.add(Math.abs(list.get(i) - list.get(j)));
}
}
写在python
中的解决方案elements = [1,4,10,17,20,35]
differences = []
for i , element in enumerate(elements):
for j, element2 in enumerate(elements):
if i != j:
differences.append( abs(element - element2) )
A Python 1 行:
>>> [abs(a - b) for i,a in enumerate(x) for j,b in enumerate(x) if i != j]
[3, 9, 16, 19, 34, 3, 6, 13, 16, 31, 9, 6, 7, 10, 25, 16, 13, 7, 3, 18, 19, 16, 10, 3, 15, 34, 31, 25, 18, 15]