英文:
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)))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论