【问题标题】:How to add multiple numbers in one string (python) [closed]如何在一个字符串中添加多个数字(python)[关闭]
【发布时间】:2021-06-23 15:56:53
【问题描述】:

假设我想给变量“e”中的所有数字加 11。我该怎么做?

ans = input("Enter here string of numbers here") 
add = input("How much do you want to add each individual numbers by: ")  #here is when it will minus each individual number print(output)

e = "21,45,42,71"

所以现在应该说(在添加 11 并打印之后)

32,56,53,82

代码:

ans = input("Enter string of numbers here")
add = input("How much do you want to add each individual numbers by: ")

#here is when it will minus each individual number
print(output)```

【问题讨论】:

  • 我们很高兴您和我们在一起,我们需要查看您的代码,以便我们帮助您修复它。
  • 您使用字符串存储数字有什么原因吗?为什么不直接列出?
  • 我没有使用列表,因为它是用来输入的

标签: python python-3.x string numbers


【解决方案1】:

试试这个:

a= "21,45,42,71" #your string
lst = list(map(int,a.split(","))) #splitted every number and converted to int and stored in list
result = list(map(lambda x:x+11,lst)) #added 11 to each number
print(result) 

【讨论】:

  • 是的,谢谢!
  • 是的,欢迎,请接受答案..
  • 我正要这样做,但它说我必须等待,别担心,因为我接受了它
【解决方案2】:

首先,拆分术语,然后将它们转换为整数,添加它们,然后将它们转换回字符串,然后打印它们。

ans = input("Enter here string of numbers here: ").split(",") 
add = input("How much do you want to add each individual numbers by: ")
print("Here is the sum: ",','.join([str(int(answer)+int(add)) for answer in ans]))

这是代码的主要部分:

','.join([str(int(answer)+int(add)) for answer in ans])

join 操作员需要一个 string 列表和另一个字符串来加入它们。

这里,[str(int(answer)+int(add)) for answer in ans] 表示将answer 和add 转换为整数,将它们相加,然后再转换回字符串。然后,.join() 使用提供的字符串加入列表。由于提供了,,因此输出将为32,56,53,82

【讨论】:

  • 轻微挑剔:您不需要列表理解。 str.join() 采用生成器表达式并计算每个元素,因此您可以保存一次遍历列表
【解决方案3】:

您可以将它用于字符串输入 => 字符串输出:

e = "21,45,42,71"

','.join([str(int(x)+11) for x in e.split(',')])
# Out[29]: '32,56,53,82'

输入整数列表 => 整数列表:

e = [21, 45, 42, 71]

[x+11 for x in e]
# Out[33]: [32, 56, 53, 82]

输入整数列表 => 整数列表(带库)

e = [21, 45, 42, 71]

import numpy as np
np.add(e, 11).tolist()

【讨论】:

  • 虽然只有代码的答案可能会回答这个问题,但您可以通过为您的代码提供上下文、此代码工作的原因以及一些文档参考以供进一步阅读,从而显着提高您的答案质量.来自How to Answer:“简洁是可以接受的,但更全面的解释更好。”
【解决方案4】:

尝试一些列表理解

ans = input("Enter here string of numbers here: ") 
add = input("How much do you want to add each individual numbers by: ")

nums = [int(x)+int(add) for x in ans.split(',')]
print(nums)

出来

Enter here string of numbers here:  23,24,25,26
How much do you want to add each individual numbers by:  11
[34, 35, 36, 37]

【讨论】:

  • @PranavHosangadi Ha
【解决方案5】:

如果您需要将结果作为单个字符串:

output = ",".join(str(int(add) + int(x)) for x in ans.split(","))
print(output)

如果您对结果是数字列表感到满意:

putput = [int(add) + int(x) for x in ans.split(",")]
print(output)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    相关资源
    最近更新 更多