1. 使用加号(`+`)运算符直接相加两个数字:
```python
num1 = 1.5
num2 = 2.5
sum = num1 + num2
print("数字 {0} 和 {1} 相加结果为: {2}".format(num1, num2, sum))
2. 使用内置的`sum()`函数对数字列表求和:
```python
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print("列表中的数字相加结果为:", total)
3. 对于整数,可以使用`sum_digits()`函数计算各位数字之和:
```python
def sum_digits(n):
str_n = str(abs(n))
return sum(int(digit) for digit in str_n)
number = -12345
print("整数 {0} 的各位数字之和为: {1}".format(number, sum_digits(number)))
4. 对于链表表示的数字,可以使用`addTwoNumbers()`函数进行相加:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def addTwoNumbers(l1, l2):
target = ListNode(0)
p = target
carry = 0
while l1 or l2:
total = carry
if l1:
total += l1.val
l1 = l1.next
if l2:
total += l2.val
l2 = l2.next
carry = total // 10
p.next = ListNode(total % 10)
p = p.next
if carry > 0:
p.next = ListNode(carry)
return target.next
5. 对于列表中的数字求和,可以使用列表生成式或`map()`函数:
```python
list_1 = [1, 2, 3]
list_2 = [4, 5, 6]
使用加号直接相加
list_3 = [x + y for x, y in zip(list_1, list_2)]
print(list_3) 输出:[5, 7, 9]
使用 map() 函数
list_3 = list(map(lambda x, y: x + y, list_1, list_2))
print(list_3) 输出:[5, 7, 9]
以上是Python中数字相加的一些常见方法。您可以根据具体需求选择合适的方法