[英]How to multiple a digit in a string by its position in the string in python
例如,如果我有 3456789,我希望總和 = (3x1) + (4x2) + (5x3) + (6x4) + (7x5) 等。
您可以使用 enumerate 獲取索引以及每個字符和總和 function 以添加產品:
sum(int(digit)*pos for pos,digit in enumerate("3456789",1)) # 196
這里有一些提示,但沒有直接回答您的問題,因為它看起來像是一項家庭作業:
for i, c in enumerate(your_string):
print("pos %d is char %s" % (i, c))
x_str = '1'
x_int = int(x_str)
此代碼計算每個值的平方和:
elems = [ 10, 15, 20, 25 ]
value = 0
for index, elem in enumerate(elems):
value = elem * elem
print("Sum of products of %s is: %d" % (elems, value))
或者你可以這樣做:
value = sum(map(lambda x: x*x, elems))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.