2014-12-06 74 views
-8

我想合計數字。在Java中添加數字

(java.numbers)

+0

那你的輸出結果如何?你爲此嘗試了什麼? – 2014-12-06 21:19:32

+1

這是你遇到麻煩的部分,還是你只想爲你寫的代碼? – 2014-12-06 21:20:02

+0

我想要一個精美的蘇格蘭威士忌和一個帶薪月份。這個很有趣! – 2015-09-11 17:00:04

回答

1

可以用切片

a = ("jim", [2,3,4,6]) 
sum(a[1][:-1])    only will work if the number in order, else need to use sorted 

演示:

>>> a=("jim", [2,3,4,6]) 
>>> a[1] 
[2, 3, 4, 6] 
>>> a[1][:-1] 
[2, 3, 4] 
>>> sum(a[1][:-1])  # sum will give sum of element in list 
9 
>>> print a[0],sum(a[1][:-1]) 
jim 9 

功能:

>>> def my_function(*a):  # *a is called splat operator, can catch any number of argument in tuple 
...  return a[0],sum(sorted(a[1][:-1]))  #sorted will sort the list, so that largest number goes at end of list, so we can exclude it 
... 
>>> my_function("jim", [2,3,4,6]) 
('jim', 9) 
0

下面是一些代碼,會做什麼你正在尋找。

l = ("jim", [2,3,4,6]) 
def totalAndDisplay(l): 
    l[1].sort() 
    print l[0],sum(l[1][:-1]) 
+0

其中,您已經重新定義了內置求和函數 – saulspatz 2014-12-06 23:12:12

+1

這需要一個參數'l',然後立即重新定義它 – TankorSmash 2014-12-06 23:53:47