简体   繁体   English

基于列表的打印 python 删除最后一个逗号

[英]List based printing python removing the last comma

I have a list of elements : answer = [1,4,2,4] I need to output the list elements two at a time with spaces separated by a comma: EXPECTED OUTPUT : 1 4,2 4我有一个元素列表:answer = [1,4,2,4] 我需要一次输出两个列表元素,用逗号分隔空格:预期输出:1 4,2 4

CODE:代码:

for i in range(0,len(ans),2):
    print(ans[i],ans[i+1],end=",")

Output: 1 4,2 4, I cannot remove that last frigging comma.输出: 1 4,2 4,我无法删除最后一个该死的逗号。

Assumption: The list is even.假设:列表是偶数。

Logic: Just detect the last iteration of the code and don't print comma there.逻辑:只检测代码的最后一次迭代,不要在那里打印逗号。

ans = [1,5,6,7,8,9]

for i in range(0,len(ans),2):

  last_iteration = len(ans)-(2) # Here 2(is same as the step size used in the loop)

  if i==last_iteration:  
    print(ans[i],ans[i+1])

  else: 
    print(ans[i],ans[i+1],end=",")

Output:输出:

1 5,6 7,8 9

This works这有效

ans = [1,4,2,4]
print(",".join([str(ans[i])+ " " + str(ans[i+1]) for i in range(0, len(ans),2)]))
>>> 1 4,2 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM