【问题标题】:Python- Printing sequence of integers separated by commasPython-打印用逗号分隔的整数序列
【发布时间】:2021-10-12 18:08:36
【问题描述】:
L=input().split(' ')
for i in L:
  c=float(i)
  print(int(c), sep=",")

用户接受一个由空格分隔的数字序列,将数字转换为小于或等于该数字的最大整数,然后打印。 我想在同一行打印输出,但我的代码不起作用

提前谢谢....

【问题讨论】:

  • 缩进你的打印声明
  • @randomer64 在这种情况下,他们还需要将sep 更改为end

标签: python string printing


【解决方案1】:

您正在遍历列表,更改为浮点数并将其放入变量c。这个循环本质上是没有意义的。在该循环之后c 包含迭代中的最后一个值。只需一次打印结果:

L=input().split(' ')
all_ints = map(int, L)
print(*all_ints, sep=',')

或者使用str.join:

print(','.join(map(str, all_ints)))

或者使用循环:

for i in all_ints:
    print(i, end=',')

要将它们全部设为floats,您也可以使用map

all_floats = list(map(float, L))

【讨论】:

    【解决方案2】:

    我认为这应该适合你:

    L = input().split(' ')
    for i in L:
      c = float(i)
      print(int(c), end=" ")
    

    【讨论】:

      猜你喜欢
      • 2021-07-20
      • 2011-11-23
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      相关资源
      最近更新 更多