如何存储多个数字,然后添加到每个数字

时间:2015-09-12 15:34:22

标签: python loops

我写了一个for循环,它给了我字母表中特定字母的所有值。

例如单词 hello 会给我8,8,12,12和14号。现在我想将它们添加到另一个单词中,例如 abcde ,这将是1,2,3,4和5.现在我想将两个数字加在一起,但保留个别数字,例如8 + 1,5 + 2,12 + 3,12 + 4和14 + 5。

这是我到目前为止的代码

for letter in message:
    if letter.isalpha() == True:
        x = alphabet.find(letter)

for letter in newkeyword:
    if letter.isalpha() == True:
        y = alphabet.find(letter)

当我尝试添加xy时,我会收到一个号码。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

您正在寻找zip功能。它拉链 2个或更多个迭代在一起。对于例如

l1 = 'abc'
l2 = 'def'
zip(l1, l2)
# [('a', 'd'), ('b', 'e'), ('c', 'f')] in python 2.7

list(zip(l1, l2))
# [('a', 'd'), ('b', 'e'), ('c', 'f')] in python 3    

所以这是解决问题的方法:

l = list(zip(message, newkeyword))
[str(alphabet.find(x)) + '+' + str(alphabet.find(y)) for x, y in l]

答案 1 :(得分:0)

如果您计划使用数字进行进一步计算,请考虑使用此解决方案创建元组列表(也可以使用zip,如@Kashyap Maduri所建议的那样):

messages = zip(message, newkeyword)
positions = [(alphabet.find(m), alphabet.find(n)) for m, n in messages]
sums = [(a, b, a + b, "{}+{}".format(a,b)) for a, b in positions]

总和列表中的每个元组都包含操作数,它们的总和以及添加的字符串表示 然后你可以打印它们的总和:

for a, b, sum_ab, sum_as_str in sorted(sums, key = lambda x: x[2]):
    print(sum_as_str)

修改

  

当我运行该程序时,我希望它能给我这些总和的答案,例如14 + 5 = 19我只想要19个部分的任何想法? - Shahzaib Shuz Bari

这使它变得更容易:

messages = zip(message, newkeyword)
sums = [alphabet.find(m) + alphabet.find(n) for m, n in messages]

你得到了所有款项的清单。

相关问题