【问题标题】:Save a data in different variable in a list ,in python在python中将数据保存在列表中的不同变量中
【发布时间】:2020-11-12 11:54:37
【问题描述】:
amount = int(input())

for i in range(amount):
    x = input().split()
    y = ([int(i) for i in x])
    z = y[0] + y[1]
    print("Result = ",z)
if i input amount = 3
and x = 2 3
        4 5
        7 8

上面的代码将打印出来:

Result  = 6
Result  = 9
Result  = 15

但我希望它像这样打印:

Result = 6 9 15

所以我的想法是将 sum 的每个结果保存到不同的变量并打印它们,但我不知道该怎么做。我知道请告诉我。或者如果你有更好的主意。

【问题讨论】:

  • 要么打印不带换行符,要么存储在列表中并打印合并结果...
  • 欢迎来到 Stackoverflow!提出问题时,请尝试正确格式化您的代码并良好地组织您的文本。例如,不要在代码 sn-p 中放置一些描述所需输出的文本。
  • 只是为了好玩,将整个代码作为一个单行代码:print(f"Result = {' '.join(map(str, [sum(map(int, input().split()[:2])) for _ in range(int(input()))]))}")
  • "所以我的想法是将 sum 的每个结果保存到不同的变量中" 您是否尝试将 x 输入中的每个整数保存到不同的变量中?为什么不?你做了什么?你能想出一种再次应用该技术的方法,以便将所有 z 值放在一起吗?

标签: python python-3.x loops for-loop sum


【解决方案1】:

更简洁的解决方案是将结果 z 存储在列表中并在循环外打印总和

amount = int(input())
z = []
for i in range(amount):
    x = input().split()
    y = ([int(i) for i in x])
    z.append(str(y[0] + y[1]))

print("Result = ", " ".join(z))

【讨论】:

  • 但请注意措辞。你没有array,你有list
  • 最后我使用[print(i) for i in z],所以输出将在数组中
【解决方案2】:

改变

print("Result = ", z)

print(" ", z, end="", flush=True)

并添加一个

print("Result =", end ="", flush=False)

在for循环之前

您也可以离开 flush = true,在 for 循环后添加一个空的 print() 调用。

【讨论】:

  • 什么是语法刷新?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-22
  • 2021-10-04
  • 1970-01-01
  • 2019-01-22
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
相关资源
最近更新 更多