如何将值列表附加到所需的字符串格式中?

huangapple go评论72阅读模式
英文:

How to append list of values into a desired string format?

问题

out_str = ''.join(out)
print(out_str)
英文:

I have two lists like below. I want to convert the list of values into a desired string format like '123,1345;2345,890;'. I tried to use loop and tried to append as list but how do I convert that into a string format.

l1 = [123,4567,80,3456,879]
l2=[98,789,5674,678,9087]

out=[]
for i,j in zip(l1,l2):
    out.append(str(j)+','+str(i)+';')
print(out)
['98,123;', '789,4567;', '5674,80;', '678,3456;', '9087,879;']

Excepted output:-

'98,123;789,4567;5674,80;678,3456;9087,879;'

答案1

得分: 1

l1 = [123, 4567, 80, 3456, 879]
l2 = [98, 789, 5674, 678, 9087]

out = []
for i, j in zip(l1, l2):
    out.append(str(j) + ',' + str(i))
print(';'.join(out) + ";")
英文:
l1 = [123,4567,80,3456,879]
l2=[98,789,5674,678,9087]

out=[]
for i,j in zip(l1,l2):
    out.append(str(j)+','+str(i))
print(';'.join(out) + ";")

You can join your list with ; to get the desired output

答案2

得分: 0

可以使用列表推导,然后解包到一个单独的 print() 调用中。

l1 = [123,4567,80,3456,879]
l2 = [98,789,5674,678,9087]

print(*[f'{b},{a};' for a, b in zip(l1, l2)], sep='')

输出:

98,123;789,4567;5674,80;678,3456;9087,879;

或者,使用生成器:

print(''.join(f'{b},{a};' for a, b in zip(l1, l2)))
英文:

You could use a list comprehension that you then unpack into a single print() call.

l1 = [123,4567,80,3456,879]
l2 = [98,789,5674,678,9087]

print(*[f'{b},{a};' for a, b in zip(l1, l2)], sep='')

Output:

98,123;789,4567;5674,80;678,3456;9087,879;

Or, with a generator:

print(''.join(f'{b},{a};' for a, b in zip(l1, l2)))

huangapple
  • 本文由 发表于 2023年2月23日 22:19:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定